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