1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/fs/file_table.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 * 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/init.h>
13 #include <linux/module.h>
14 #include <linux/fs.h>
15 #include <linux/filelock.h>
16 #include <linux/security.h>
17 #include <linux/cred.h>
18 #include <linux/eventpoll.h>
19 #include <linux/rcupdate.h>
20 #include <linux/mount.h>
21 #include <linux/capability.h>
22 #include <linux/cdev.h>
23 #include <linux/fsnotify.h>
24 #include <linux/sysctl.h>
25 #include <linux/percpu_counter.h>
26 #include <linux/percpu.h>
27 #include <linux/task_work.h>
28 #include <linux/swap.h>
29 #include <linux/kmemleak.h>
30
31 #include <linux/atomic.h>
32
33 #include "internal.h"
34
35 /* sysctl tunables... */
36 static struct files_stat_struct files_stat = {
37 .max_files = NR_FILE
38 };
39
40 /* SLAB cache for file structures */
41 static struct kmem_cache *filp_cachep __ro_after_init;
42 static struct kmem_cache *bfilp_cachep __ro_after_init;
43
44 static struct percpu_counter nr_files __cacheline_aligned_in_smp;
45
46 /* Container for backing file with optional user path */
47 struct backing_file {
48 struct file file;
49 union {
50 struct path user_path;
51 freeptr_t bf_freeptr;
52 };
53 };
54
55 #define backing_file(f) container_of(f, struct backing_file, file)
56
backing_file_user_path(const struct file * f)57 const struct path *backing_file_user_path(const struct file *f)
58 {
59 return &backing_file(f)->user_path;
60 }
61 EXPORT_SYMBOL_GPL(backing_file_user_path);
62
backing_file_set_user_path(struct file * f,const struct path * path)63 void backing_file_set_user_path(struct file *f, const struct path *path)
64 {
65 backing_file(f)->user_path = *path;
66 }
67 EXPORT_SYMBOL_GPL(backing_file_set_user_path);
68
file_free(struct file * f)69 static inline void file_free(struct file *f)
70 {
71 security_file_free(f);
72 if (likely(!(f->f_mode & FMODE_NOACCOUNT)))
73 percpu_counter_dec(&nr_files);
74 put_cred(f->f_cred);
75 if (unlikely(f->f_mode & FMODE_BACKING)) {
76 path_put(backing_file_user_path(f));
77 kmem_cache_free(bfilp_cachep, backing_file(f));
78 } else {
79 kmem_cache_free(filp_cachep, f);
80 }
81 }
82
83 /*
84 * Return the total number of open files in the system
85 */
get_nr_files(void)86 static long get_nr_files(void)
87 {
88 return percpu_counter_read_positive(&nr_files);
89 }
90
91 /*
92 * Return the maximum number of open files in the system
93 */
get_max_files(void)94 unsigned long get_max_files(void)
95 {
96 return files_stat.max_files;
97 }
98 EXPORT_SYMBOL_GPL(get_max_files);
99
100 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
101
102 /*
103 * Handle nr_files sysctl
104 */
proc_nr_files(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)105 static int proc_nr_files(const struct ctl_table *table, int write, void *buffer,
106 size_t *lenp, loff_t *ppos)
107 {
108 files_stat.nr_files = percpu_counter_sum_positive(&nr_files);
109 return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
110 }
111
112 static const struct ctl_table fs_stat_sysctls[] = {
113 {
114 .procname = "file-nr",
115 .data = &files_stat,
116 .maxlen = sizeof(files_stat),
117 .mode = 0444,
118 .proc_handler = proc_nr_files,
119 },
120 {
121 .procname = "file-max",
122 .data = &files_stat.max_files,
123 .maxlen = sizeof(files_stat.max_files),
124 .mode = 0644,
125 .proc_handler = proc_doulongvec_minmax,
126 .extra1 = SYSCTL_LONG_ZERO,
127 .extra2 = SYSCTL_LONG_MAX,
128 },
129 {
130 .procname = "nr_open",
131 .data = &sysctl_nr_open,
132 .maxlen = sizeof(unsigned int),
133 .mode = 0644,
134 .proc_handler = proc_douintvec_minmax,
135 .extra1 = &sysctl_nr_open_min,
136 .extra2 = &sysctl_nr_open_max,
137 },
138 };
139
init_fs_stat_sysctls(void)140 static int __init init_fs_stat_sysctls(void)
141 {
142 register_sysctl_init("fs", fs_stat_sysctls);
143 if (IS_ENABLED(CONFIG_BINFMT_MISC)) {
144 struct ctl_table_header *hdr;
145
146 hdr = register_sysctl_mount_point("fs/binfmt_misc");
147 kmemleak_not_leak(hdr);
148 }
149 return 0;
150 }
151 fs_initcall(init_fs_stat_sysctls);
152 #endif
153
init_file(struct file * f,int flags,const struct cred * cred)154 static int init_file(struct file *f, int flags, const struct cred *cred)
155 {
156 int error;
157
158 f->f_cred = get_cred(cred);
159 error = security_file_alloc(f);
160 if (unlikely(error)) {
161 put_cred(f->f_cred);
162 return error;
163 }
164
165 spin_lock_init(&f->f_lock);
166 /*
167 * Note that f_pos_lock is only used for files raising
168 * FMODE_ATOMIC_POS and directories. Other files such as pipes
169 * don't need it and since f_pos_lock is in a union may reuse
170 * the space for other purposes. They are expected to initialize
171 * the respective member when opening the file.
172 */
173 mutex_init(&f->f_pos_lock);
174 memset(&f->__f_path, 0, sizeof(f->f_path));
175 memset(&f->f_ra, 0, sizeof(f->f_ra));
176
177 f->f_flags = flags;
178 f->f_mode = OPEN_FMODE(flags);
179 /*
180 * Disable permission and pre-content events for all files by default.
181 * They may be enabled later by fsnotify_open_perm_and_set_mode().
182 */
183 file_set_fsnotify_mode(f, FMODE_NONOTIFY_PERM);
184
185 f->f_op = NULL;
186 f->f_mapping = NULL;
187 f->private_data = NULL;
188 f->f_inode = NULL;
189 f->f_owner = NULL;
190 #ifdef CONFIG_EPOLL
191 f->f_ep = NULL;
192 #endif
193
194 f->f_iocb_flags = 0;
195 f->f_pos = 0;
196 f->f_wb_err = 0;
197 f->f_sb_err = 0;
198
199 /*
200 * We're SLAB_TYPESAFE_BY_RCU so initialize f_ref last. While
201 * fget-rcu pattern users need to be able to handle spurious
202 * refcount bumps we should reinitialize the reused file first.
203 */
204 file_ref_init(&f->f_ref, 1);
205 return 0;
206 }
207
208 /* Find an unused file structure and return a pointer to it.
209 * Returns an error pointer if some error happend e.g. we over file
210 * structures limit, run out of memory or operation is not permitted.
211 *
212 * Be very careful using this. You are responsible for
213 * getting write access to any mount that you might assign
214 * to this filp, if it is opened for write. If this is not
215 * done, you will imbalance int the mount's writer count
216 * and a warning at __fput() time.
217 */
alloc_empty_file(int flags,const struct cred * cred)218 struct file *alloc_empty_file(int flags, const struct cred *cred)
219 {
220 static long old_max;
221 struct file *f;
222 int error;
223
224 /*
225 * Privileged users can go above max_files
226 */
227 if (unlikely(get_nr_files() >= files_stat.max_files) &&
228 !capable(CAP_SYS_ADMIN)) {
229 /*
230 * percpu_counters are inaccurate. Do an expensive check before
231 * we go and fail.
232 */
233 if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
234 goto over;
235 }
236
237 f = kmem_cache_alloc(filp_cachep, GFP_KERNEL);
238 if (unlikely(!f))
239 return ERR_PTR(-ENOMEM);
240
241 error = init_file(f, flags, cred);
242 if (unlikely(error)) {
243 kmem_cache_free(filp_cachep, f);
244 return ERR_PTR(error);
245 }
246
247 percpu_counter_inc(&nr_files);
248
249 return f;
250
251 over:
252 /* Ran out of filps - report that */
253 if (get_nr_files() > old_max) {
254 pr_info("VFS: file-max limit %lu reached\n", get_max_files());
255 old_max = get_nr_files();
256 }
257 return ERR_PTR(-ENFILE);
258 }
259
260 /*
261 * Variant of alloc_empty_file() that doesn't check and modify nr_files.
262 *
263 * This is only for kernel internal use, and the allocate file must not be
264 * installed into file tables or such.
265 */
alloc_empty_file_noaccount(int flags,const struct cred * cred)266 struct file *alloc_empty_file_noaccount(int flags, const struct cred *cred)
267 {
268 struct file *f;
269 int error;
270
271 f = kmem_cache_alloc(filp_cachep, GFP_KERNEL);
272 if (unlikely(!f))
273 return ERR_PTR(-ENOMEM);
274
275 error = init_file(f, flags, cred);
276 if (unlikely(error)) {
277 kmem_cache_free(filp_cachep, f);
278 return ERR_PTR(error);
279 }
280
281 f->f_mode |= FMODE_NOACCOUNT;
282
283 return f;
284 }
285
286 /*
287 * Variant of alloc_empty_file() that allocates a backing_file container
288 * and doesn't check and modify nr_files.
289 *
290 * This is only for kernel internal use, and the allocate file must not be
291 * installed into file tables or such.
292 */
alloc_empty_backing_file(int flags,const struct cred * cred)293 struct file *alloc_empty_backing_file(int flags, const struct cred *cred)
294 {
295 struct backing_file *ff;
296 int error;
297
298 ff = kmem_cache_alloc(bfilp_cachep, GFP_KERNEL);
299 if (unlikely(!ff))
300 return ERR_PTR(-ENOMEM);
301
302 error = init_file(&ff->file, flags, cred);
303 if (unlikely(error)) {
304 kmem_cache_free(bfilp_cachep, ff);
305 return ERR_PTR(error);
306 }
307
308 ff->file.f_mode |= FMODE_BACKING | FMODE_NOACCOUNT;
309 return &ff->file;
310 }
311 EXPORT_SYMBOL_GPL(alloc_empty_backing_file);
312
313 /**
314 * file_init_path - initialize a 'struct file' based on path
315 *
316 * @file: the file to set up
317 * @path: the (dentry, vfsmount) pair for the new file
318 * @fop: the 'struct file_operations' for the new file
319 */
file_init_path(struct file * file,const struct path * path,const struct file_operations * fop)320 static void file_init_path(struct file *file, const struct path *path,
321 const struct file_operations *fop)
322 {
323 file->__f_path = *path;
324 file->f_inode = path->dentry->d_inode;
325 file->f_mapping = path->dentry->d_inode->i_mapping;
326 file->f_wb_err = filemap_sample_wb_err(file->f_mapping);
327 file->f_sb_err = file_sample_sb_err(file);
328 if (fop->llseek)
329 file->f_mode |= FMODE_LSEEK;
330 if ((file->f_mode & FMODE_READ) &&
331 likely(fop->read || fop->read_iter))
332 file->f_mode |= FMODE_CAN_READ;
333 if ((file->f_mode & FMODE_WRITE) &&
334 likely(fop->write || fop->write_iter))
335 file->f_mode |= FMODE_CAN_WRITE;
336 file->f_iocb_flags = iocb_flags(file);
337 file->f_mode |= FMODE_OPENED;
338 file->f_op = fop;
339 if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
340 i_readcount_inc(path->dentry->d_inode);
341 }
342
343 /**
344 * alloc_file - allocate and initialize a 'struct file'
345 *
346 * @path: the (dentry, vfsmount) pair for the new file
347 * @flags: O_... flags with which the new file will be opened
348 * @fop: the 'struct file_operations' for the new file
349 */
alloc_file(const struct path * path,int flags,const struct file_operations * fop)350 static struct file *alloc_file(const struct path *path, int flags,
351 const struct file_operations *fop)
352 {
353 struct file *file;
354
355 file = alloc_empty_file(flags, current_cred());
356 if (!IS_ERR(file))
357 file_init_path(file, path, fop);
358 return file;
359 }
360
alloc_path_pseudo(const char * name,struct inode * inode,struct vfsmount * mnt,struct path * path)361 static inline int alloc_path_pseudo(const char *name, struct inode *inode,
362 struct vfsmount *mnt, struct path *path)
363 {
364 path->dentry = d_alloc_pseudo(mnt->mnt_sb, &QSTR(name));
365 if (!path->dentry)
366 return -ENOMEM;
367 path->mnt = mntget(mnt);
368 d_instantiate(path->dentry, inode);
369 return 0;
370 }
371
alloc_file_pseudo(struct inode * inode,struct vfsmount * mnt,const char * name,int flags,const struct file_operations * fops)372 struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt,
373 const char *name, int flags,
374 const struct file_operations *fops)
375 {
376 int ret;
377 struct path path;
378 struct file *file;
379
380 ret = alloc_path_pseudo(name, inode, mnt, &path);
381 if (ret)
382 return ERR_PTR(ret);
383
384 file = alloc_file(&path, flags, fops);
385 if (IS_ERR(file)) {
386 ihold(inode);
387 path_put(&path);
388 return file;
389 }
390 /*
391 * Disable all fsnotify events for pseudo files by default.
392 * They may be enabled by caller with file_set_fsnotify_mode().
393 */
394 file_set_fsnotify_mode(file, FMODE_NONOTIFY);
395 return file;
396 }
397 EXPORT_SYMBOL(alloc_file_pseudo);
398
alloc_file_pseudo_noaccount(struct inode * inode,struct vfsmount * mnt,const char * name,int flags,const struct file_operations * fops)399 struct file *alloc_file_pseudo_noaccount(struct inode *inode,
400 struct vfsmount *mnt, const char *name,
401 int flags,
402 const struct file_operations *fops)
403 {
404 int ret;
405 struct path path;
406 struct file *file;
407
408 ret = alloc_path_pseudo(name, inode, mnt, &path);
409 if (ret)
410 return ERR_PTR(ret);
411
412 file = alloc_empty_file_noaccount(flags, current_cred());
413 if (IS_ERR(file)) {
414 ihold(inode);
415 path_put(&path);
416 return file;
417 }
418 file_init_path(file, &path, fops);
419 /*
420 * Disable all fsnotify events for pseudo files by default.
421 * They may be enabled by caller with file_set_fsnotify_mode().
422 */
423 file_set_fsnotify_mode(file, FMODE_NONOTIFY);
424 return file;
425 }
426 EXPORT_SYMBOL_GPL(alloc_file_pseudo_noaccount);
427
alloc_file_clone(struct file * base,int flags,const struct file_operations * fops)428 struct file *alloc_file_clone(struct file *base, int flags,
429 const struct file_operations *fops)
430 {
431 struct file *f;
432
433 f = alloc_file(&base->f_path, flags, fops);
434 if (!IS_ERR(f)) {
435 path_get(&f->f_path);
436 f->f_mapping = base->f_mapping;
437 }
438 return f;
439 }
440
441 /* the real guts of fput() - releasing the last reference to file
442 */
__fput(struct file * file)443 static void __fput(struct file *file)
444 {
445 struct dentry *dentry = file->f_path.dentry;
446 struct vfsmount *mnt = file->f_path.mnt;
447 struct inode *inode = file->f_inode;
448 fmode_t mode = file->f_mode;
449
450 if (unlikely(!(file->f_mode & FMODE_OPENED)))
451 goto out;
452
453 might_sleep();
454
455 fsnotify_close(file);
456 /*
457 * The function eventpoll_release() should be the first called
458 * in the file cleanup chain.
459 */
460 eventpoll_release(file);
461 locks_remove_file(file);
462
463 security_file_release(file);
464 if (unlikely(file->f_flags & FASYNC)) {
465 if (file->f_op->fasync)
466 file->f_op->fasync(-1, file, 0);
467 }
468 if (file->f_op->release)
469 file->f_op->release(inode, file);
470 if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL &&
471 !(mode & FMODE_PATH))) {
472 cdev_put(inode->i_cdev);
473 }
474 fops_put(file->f_op);
475 file_f_owner_release(file);
476 put_file_access(file);
477 dput(dentry);
478 if (unlikely(mode & FMODE_NEED_UNMOUNT))
479 dissolve_on_fput(mnt);
480 mntput(mnt);
481 out:
482 file_free(file);
483 }
484
485 static LLIST_HEAD(delayed_fput_list);
delayed_fput(struct work_struct * unused)486 static void delayed_fput(struct work_struct *unused)
487 {
488 struct llist_node *node = llist_del_all(&delayed_fput_list);
489 struct file *f, *t;
490
491 llist_for_each_entry_safe(f, t, node, f_llist)
492 __fput(f);
493 }
494
____fput(struct callback_head * work)495 static void ____fput(struct callback_head *work)
496 {
497 __fput(container_of(work, struct file, f_task_work));
498 }
499
500 static DECLARE_DELAYED_WORK(delayed_fput_work, delayed_fput);
501
502 /*
503 * If kernel thread really needs to have the final fput() it has done
504 * to complete, call this. The only user right now is the boot - we
505 * *do* need to make sure our writes to binaries on initramfs has
506 * not left us with opened struct file waiting for __fput() - execve()
507 * won't work without that. Please, don't add more callers without
508 * very good reasons; in particular, never call that with locks
509 * held and never call that from a thread that might need to do
510 * some work on any kind of umount.
511 */
flush_delayed_fput(void)512 void flush_delayed_fput(void)
513 {
514 delayed_fput(NULL);
515 flush_delayed_work(&delayed_fput_work);
516 }
517 EXPORT_SYMBOL_GPL(flush_delayed_fput);
518
__fput_deferred(struct file * file)519 static void __fput_deferred(struct file *file)
520 {
521 struct task_struct *task = current;
522
523 if (unlikely(!(file->f_mode & (FMODE_BACKING | FMODE_OPENED)))) {
524 file_free(file);
525 return;
526 }
527
528 if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
529 init_task_work(&file->f_task_work, ____fput);
530 if (!task_work_add(task, &file->f_task_work, TWA_RESUME))
531 return;
532 /*
533 * After this task has run exit_task_work(),
534 * task_work_add() will fail. Fall through to delayed
535 * fput to avoid leaking *file.
536 */
537 }
538
539 if (llist_add(&file->f_llist, &delayed_fput_list))
540 schedule_delayed_work(&delayed_fput_work, 1);
541 }
542
fput(struct file * file)543 void fput(struct file *file)
544 {
545 if (unlikely(file_ref_put(&file->f_ref)))
546 __fput_deferred(file);
547 }
548 EXPORT_SYMBOL(fput);
549
550 /*
551 * synchronous analog of fput(); for kernel threads that might be needed
552 * in some umount() (and thus can't use flush_delayed_fput() without
553 * risking deadlocks), need to wait for completion of __fput() and know
554 * for this specific struct file it won't involve anything that would
555 * need them. Use only if you really need it - at the very least,
556 * don't blindly convert fput() by kernel thread to that.
557 */
__fput_sync(struct file * file)558 void __fput_sync(struct file *file)
559 {
560 if (file_ref_put(&file->f_ref))
561 __fput(file);
562 }
563 EXPORT_SYMBOL(__fput_sync);
564
565 /*
566 * Equivalent to __fput_sync(), but optimized for being called with the last
567 * reference.
568 *
569 * See file_ref_put_close() for details.
570 */
fput_close_sync(struct file * file)571 void fput_close_sync(struct file *file)
572 {
573 if (likely(file_ref_put_close(&file->f_ref)))
574 __fput(file);
575 }
576
577 /*
578 * Equivalent to fput(), but optimized for being called with the last
579 * reference.
580 *
581 * See file_ref_put_close() for details.
582 */
fput_close(struct file * file)583 void fput_close(struct file *file)
584 {
585 if (file_ref_put_close(&file->f_ref))
586 __fput_deferred(file);
587 }
588
files_init(void)589 void __init files_init(void)
590 {
591 struct kmem_cache_args args = {
592 .use_freeptr_offset = true,
593 .freeptr_offset = offsetof(struct file, f_freeptr),
594 };
595
596 filp_cachep = kmem_cache_create("filp", sizeof(struct file), &args,
597 SLAB_HWCACHE_ALIGN | SLAB_PANIC |
598 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU);
599
600 args.freeptr_offset = offsetof(struct backing_file, bf_freeptr);
601 bfilp_cachep = kmem_cache_create("bfilp", sizeof(struct backing_file),
602 &args, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
603 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU);
604 percpu_counter_init(&nr_files, 0, GFP_KERNEL);
605 }
606
607 /*
608 * One file with associated inode and dcache is very roughly 1K. Per default
609 * do not use more than 10% of our memory for files.
610 */
files_maxfiles_init(void)611 void __init files_maxfiles_init(void)
612 {
613 unsigned long n;
614 unsigned long nr_pages = totalram_pages();
615 unsigned long memreserve = (nr_pages - nr_free_pages()) * 3/2;
616
617 memreserve = min(memreserve, nr_pages - 1);
618 n = ((nr_pages - memreserve) * (PAGE_SIZE / 1024)) / 10;
619
620 files_stat.max_files = max_t(unsigned long, n, NR_FILE);
621 }
622