xref: /linux/fs/file_table.c (revision b8bb76713ec50df2f11efee386e16f93d51e1076)
1 /*
2  *  linux/fs/file_table.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  *  Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
6  */
7 
8 #include <linux/string.h>
9 #include <linux/slab.h>
10 #include <linux/file.h>
11 #include <linux/fdtable.h>
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/fs.h>
15 #include <linux/security.h>
16 #include <linux/ima.h>
17 #include <linux/eventpoll.h>
18 #include <linux/rcupdate.h>
19 #include <linux/mount.h>
20 #include <linux/capability.h>
21 #include <linux/cdev.h>
22 #include <linux/fsnotify.h>
23 #include <linux/sysctl.h>
24 #include <linux/percpu_counter.h>
25 
26 #include <asm/atomic.h>
27 
28 /* sysctl tunables... */
29 struct files_stat_struct files_stat = {
30 	.max_files = NR_FILE
31 };
32 
33 /* public. Not pretty! */
34 __cacheline_aligned_in_smp DEFINE_SPINLOCK(files_lock);
35 
36 /* SLAB cache for file structures */
37 static struct kmem_cache *filp_cachep __read_mostly;
38 
39 static struct percpu_counter nr_files __cacheline_aligned_in_smp;
40 
41 static inline void file_free_rcu(struct rcu_head *head)
42 {
43 	struct file *f = container_of(head, struct file, f_u.fu_rcuhead);
44 
45 	put_cred(f->f_cred);
46 	kmem_cache_free(filp_cachep, f);
47 }
48 
49 static inline void file_free(struct file *f)
50 {
51 	percpu_counter_dec(&nr_files);
52 	file_check_state(f);
53 	call_rcu(&f->f_u.fu_rcuhead, file_free_rcu);
54 }
55 
56 /*
57  * Return the total number of open files in the system
58  */
59 static int get_nr_files(void)
60 {
61 	return percpu_counter_read_positive(&nr_files);
62 }
63 
64 /*
65  * Return the maximum number of open files in the system
66  */
67 int get_max_files(void)
68 {
69 	return files_stat.max_files;
70 }
71 EXPORT_SYMBOL_GPL(get_max_files);
72 
73 /*
74  * Handle nr_files sysctl
75  */
76 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
77 int proc_nr_files(ctl_table *table, int write, struct file *filp,
78                      void __user *buffer, size_t *lenp, loff_t *ppos)
79 {
80 	files_stat.nr_files = get_nr_files();
81 	return proc_dointvec(table, write, filp, buffer, lenp, ppos);
82 }
83 #else
84 int proc_nr_files(ctl_table *table, int write, struct file *filp,
85                      void __user *buffer, size_t *lenp, loff_t *ppos)
86 {
87 	return -ENOSYS;
88 }
89 #endif
90 
91 /* Find an unused file structure and return a pointer to it.
92  * Returns NULL, if there are no more free file structures or
93  * we run out of memory.
94  *
95  * Be very careful using this.  You are responsible for
96  * getting write access to any mount that you might assign
97  * to this filp, if it is opened for write.  If this is not
98  * done, you will imbalance int the mount's writer count
99  * and a warning at __fput() time.
100  */
101 struct file *get_empty_filp(void)
102 {
103 	const struct cred *cred = current_cred();
104 	static int old_max;
105 	struct file * f;
106 
107 	/*
108 	 * Privileged users can go above max_files
109 	 */
110 	if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
111 		/*
112 		 * percpu_counters are inaccurate.  Do an expensive check before
113 		 * we go and fail.
114 		 */
115 		if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
116 			goto over;
117 	}
118 
119 	f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
120 	if (f == NULL)
121 		goto fail;
122 
123 	percpu_counter_inc(&nr_files);
124 	if (security_file_alloc(f))
125 		goto fail_sec;
126 
127 	INIT_LIST_HEAD(&f->f_u.fu_list);
128 	atomic_long_set(&f->f_count, 1);
129 	rwlock_init(&f->f_owner.lock);
130 	f->f_cred = get_cred(cred);
131 	spin_lock_init(&f->f_lock);
132 	eventpoll_init_file(f);
133 	/* f->f_version: 0 */
134 	return f;
135 
136 over:
137 	/* Ran out of filps - report that */
138 	if (get_nr_files() > old_max) {
139 		printk(KERN_INFO "VFS: file-max limit %d reached\n",
140 					get_max_files());
141 		old_max = get_nr_files();
142 	}
143 	goto fail;
144 
145 fail_sec:
146 	file_free(f);
147 fail:
148 	return NULL;
149 }
150 
151 EXPORT_SYMBOL(get_empty_filp);
152 
153 /**
154  * alloc_file - allocate and initialize a 'struct file'
155  * @mnt: the vfsmount on which the file will reside
156  * @dentry: the dentry representing the new file
157  * @mode: the mode with which the new file will be opened
158  * @fop: the 'struct file_operations' for the new file
159  *
160  * Use this instead of get_empty_filp() to get a new
161  * 'struct file'.  Do so because of the same initialization
162  * pitfalls reasons listed for init_file().  This is a
163  * preferred interface to using init_file().
164  *
165  * If all the callers of init_file() are eliminated, its
166  * code should be moved into this function.
167  */
168 struct file *alloc_file(struct vfsmount *mnt, struct dentry *dentry,
169 		fmode_t mode, const struct file_operations *fop)
170 {
171 	struct file *file;
172 	struct path;
173 
174 	file = get_empty_filp();
175 	if (!file)
176 		return NULL;
177 
178 	init_file(file, mnt, dentry, mode, fop);
179 	return file;
180 }
181 EXPORT_SYMBOL(alloc_file);
182 
183 /**
184  * init_file - initialize a 'struct file'
185  * @file: the already allocated 'struct file' to initialized
186  * @mnt: the vfsmount on which the file resides
187  * @dentry: the dentry representing this file
188  * @mode: the mode the file is opened with
189  * @fop: the 'struct file_operations' for this file
190  *
191  * Use this instead of setting the members directly.  Doing so
192  * avoids making mistakes like forgetting the mntget() or
193  * forgetting to take a write on the mnt.
194  *
195  * Note: This is a crappy interface.  It is here to make
196  * merging with the existing users of get_empty_filp()
197  * who have complex failure logic easier.  All users
198  * of this should be moving to alloc_file().
199  */
200 int init_file(struct file *file, struct vfsmount *mnt, struct dentry *dentry,
201 	   fmode_t mode, const struct file_operations *fop)
202 {
203 	int error = 0;
204 	file->f_path.dentry = dentry;
205 	file->f_path.mnt = mntget(mnt);
206 	file->f_mapping = dentry->d_inode->i_mapping;
207 	file->f_mode = mode;
208 	file->f_op = fop;
209 
210 	/*
211 	 * These mounts don't really matter in practice
212 	 * for r/o bind mounts.  They aren't userspace-
213 	 * visible.  We do this for consistency, and so
214 	 * that we can do debugging checks at __fput()
215 	 */
216 	if ((mode & FMODE_WRITE) && !special_file(dentry->d_inode->i_mode)) {
217 		file_take_write(file);
218 		error = mnt_want_write(mnt);
219 		WARN_ON(error);
220 	}
221 	return error;
222 }
223 EXPORT_SYMBOL(init_file);
224 
225 void fput(struct file *file)
226 {
227 	if (atomic_long_dec_and_test(&file->f_count))
228 		__fput(file);
229 }
230 
231 EXPORT_SYMBOL(fput);
232 
233 /**
234  * drop_file_write_access - give up ability to write to a file
235  * @file: the file to which we will stop writing
236  *
237  * This is a central place which will give up the ability
238  * to write to @file, along with access to write through
239  * its vfsmount.
240  */
241 void drop_file_write_access(struct file *file)
242 {
243 	struct vfsmount *mnt = file->f_path.mnt;
244 	struct dentry *dentry = file->f_path.dentry;
245 	struct inode *inode = dentry->d_inode;
246 
247 	put_write_access(inode);
248 
249 	if (special_file(inode->i_mode))
250 		return;
251 	if (file_check_writeable(file) != 0)
252 		return;
253 	mnt_drop_write(mnt);
254 	file_release_write(file);
255 }
256 EXPORT_SYMBOL_GPL(drop_file_write_access);
257 
258 /* __fput is called from task context when aio completion releases the last
259  * last use of a struct file *.  Do not use otherwise.
260  */
261 void __fput(struct file *file)
262 {
263 	struct dentry *dentry = file->f_path.dentry;
264 	struct vfsmount *mnt = file->f_path.mnt;
265 	struct inode *inode = dentry->d_inode;
266 
267 	might_sleep();
268 
269 	fsnotify_close(file);
270 	/*
271 	 * The function eventpoll_release() should be the first called
272 	 * in the file cleanup chain.
273 	 */
274 	eventpoll_release(file);
275 	locks_remove_flock(file);
276 
277 	if (unlikely(file->f_flags & FASYNC)) {
278 		if (file->f_op && file->f_op->fasync)
279 			file->f_op->fasync(-1, file, 0);
280 	}
281 	if (file->f_op && file->f_op->release)
282 		file->f_op->release(inode, file);
283 	security_file_free(file);
284 	ima_file_free(file);
285 	if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL))
286 		cdev_put(inode->i_cdev);
287 	fops_put(file->f_op);
288 	put_pid(file->f_owner.pid);
289 	file_kill(file);
290 	if (file->f_mode & FMODE_WRITE)
291 		drop_file_write_access(file);
292 	file->f_path.dentry = NULL;
293 	file->f_path.mnt = NULL;
294 	file_free(file);
295 	dput(dentry);
296 	mntput(mnt);
297 }
298 
299 struct file *fget(unsigned int fd)
300 {
301 	struct file *file;
302 	struct files_struct *files = current->files;
303 
304 	rcu_read_lock();
305 	file = fcheck_files(files, fd);
306 	if (file) {
307 		if (!atomic_long_inc_not_zero(&file->f_count)) {
308 			/* File object ref couldn't be taken */
309 			rcu_read_unlock();
310 			return NULL;
311 		}
312 	}
313 	rcu_read_unlock();
314 
315 	return file;
316 }
317 
318 EXPORT_SYMBOL(fget);
319 
320 /*
321  * Lightweight file lookup - no refcnt increment if fd table isn't shared.
322  * You can use this only if it is guranteed that the current task already
323  * holds a refcnt to that file. That check has to be done at fget() only
324  * and a flag is returned to be passed to the corresponding fput_light().
325  * There must not be a cloning between an fget_light/fput_light pair.
326  */
327 struct file *fget_light(unsigned int fd, int *fput_needed)
328 {
329 	struct file *file;
330 	struct files_struct *files = current->files;
331 
332 	*fput_needed = 0;
333 	if (likely((atomic_read(&files->count) == 1))) {
334 		file = fcheck_files(files, fd);
335 	} else {
336 		rcu_read_lock();
337 		file = fcheck_files(files, fd);
338 		if (file) {
339 			if (atomic_long_inc_not_zero(&file->f_count))
340 				*fput_needed = 1;
341 			else
342 				/* Didn't get the reference, someone's freed */
343 				file = NULL;
344 		}
345 		rcu_read_unlock();
346 	}
347 
348 	return file;
349 }
350 
351 
352 void put_filp(struct file *file)
353 {
354 	if (atomic_long_dec_and_test(&file->f_count)) {
355 		security_file_free(file);
356 		file_kill(file);
357 		file_free(file);
358 	}
359 }
360 
361 void file_move(struct file *file, struct list_head *list)
362 {
363 	if (!list)
364 		return;
365 	file_list_lock();
366 	list_move(&file->f_u.fu_list, list);
367 	file_list_unlock();
368 }
369 
370 void file_kill(struct file *file)
371 {
372 	if (!list_empty(&file->f_u.fu_list)) {
373 		file_list_lock();
374 		list_del_init(&file->f_u.fu_list);
375 		file_list_unlock();
376 	}
377 }
378 
379 int fs_may_remount_ro(struct super_block *sb)
380 {
381 	struct file *file;
382 
383 	/* Check that no files are currently opened for writing. */
384 	file_list_lock();
385 	list_for_each_entry(file, &sb->s_files, f_u.fu_list) {
386 		struct inode *inode = file->f_path.dentry->d_inode;
387 
388 		/* File with pending delete? */
389 		if (inode->i_nlink == 0)
390 			goto too_bad;
391 
392 		/* Writeable file? */
393 		if (S_ISREG(inode->i_mode) && (file->f_mode & FMODE_WRITE))
394 			goto too_bad;
395 	}
396 	file_list_unlock();
397 	return 1; /* Tis' cool bro. */
398 too_bad:
399 	file_list_unlock();
400 	return 0;
401 }
402 
403 void __init files_init(unsigned long mempages)
404 {
405 	int n;
406 
407 	filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
408 			SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
409 
410 	/*
411 	 * One file with associated inode and dcache is very roughly 1K.
412 	 * Per default don't use more than 10% of our memory for files.
413 	 */
414 
415 	n = (mempages * (PAGE_SIZE / 1024)) / 10;
416 	files_stat.max_files = n;
417 	if (files_stat.max_files < NR_FILE)
418 		files_stat.max_files = NR_FILE;
419 	files_defer_init();
420 	percpu_counter_init(&nr_files, 0);
421 }
422