xref: /linux/fs/file.c (revision a5161eeef97cb0cdc4de966005926db2f5894af4)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/file.c
4  *
5  *  Copyright (C) 1998-1999, Stephen Tweedie and Bill Hawes
6  *
7  *  Manage the dynamic fd arrays in the process files_struct.
8  */
9 
10 #include <linux/syscalls.h>
11 #include <linux/export.h>
12 #include <linux/fs.h>
13 #include <linux/kernel.h>
14 #include <linux/mm.h>
15 #include <linux/sched/signal.h>
16 #include <linux/slab.h>
17 #include <linux/file.h>
18 #include <linux/fdtable.h>
19 #include <linux/bitops.h>
20 #include <linux/spinlock.h>
21 #include <linux/rcupdate.h>
22 #include <linux/close_range.h>
23 
24 unsigned int sysctl_nr_open __read_mostly = 1024*1024;
25 unsigned int sysctl_nr_open_min = BITS_PER_LONG;
26 /* our min() is unusable in constant expressions ;-/ */
27 #define __const_min(x, y) ((x) < (y) ? (x) : (y))
28 unsigned int sysctl_nr_open_max =
29 	__const_min(INT_MAX, ~(size_t)0/sizeof(void *)) & -BITS_PER_LONG;
30 
31 static void __free_fdtable(struct fdtable *fdt)
32 {
33 	kvfree(fdt->fd);
34 	kvfree(fdt->open_fds);
35 	kfree(fdt);
36 }
37 
38 static void free_fdtable_rcu(struct rcu_head *rcu)
39 {
40 	__free_fdtable(container_of(rcu, struct fdtable, rcu));
41 }
42 
43 #define BITBIT_NR(nr)	BITS_TO_LONGS(BITS_TO_LONGS(nr))
44 #define BITBIT_SIZE(nr)	(BITBIT_NR(nr) * sizeof(long))
45 
46 /*
47  * Copy 'count' fd bits from the old table to the new table and clear the extra
48  * space if any.  This does not copy the file pointers.  Called with the files
49  * spinlock held for write.
50  */
51 static void copy_fd_bitmaps(struct fdtable *nfdt, struct fdtable *ofdt,
52 			    unsigned int count)
53 {
54 	unsigned int cpy, set;
55 
56 	cpy = count / BITS_PER_BYTE;
57 	set = (nfdt->max_fds - count) / BITS_PER_BYTE;
58 	memcpy(nfdt->open_fds, ofdt->open_fds, cpy);
59 	memset((char *)nfdt->open_fds + cpy, 0, set);
60 	memcpy(nfdt->close_on_exec, ofdt->close_on_exec, cpy);
61 	memset((char *)nfdt->close_on_exec + cpy, 0, set);
62 
63 	cpy = BITBIT_SIZE(count);
64 	set = BITBIT_SIZE(nfdt->max_fds) - cpy;
65 	memcpy(nfdt->full_fds_bits, ofdt->full_fds_bits, cpy);
66 	memset((char *)nfdt->full_fds_bits + cpy, 0, set);
67 }
68 
69 /*
70  * Copy all file descriptors from the old table to the new, expanded table and
71  * clear the extra space.  Called with the files spinlock held for write.
72  */
73 static void copy_fdtable(struct fdtable *nfdt, struct fdtable *ofdt)
74 {
75 	size_t cpy, set;
76 
77 	BUG_ON(nfdt->max_fds < ofdt->max_fds);
78 
79 	cpy = ofdt->max_fds * sizeof(struct file *);
80 	set = (nfdt->max_fds - ofdt->max_fds) * sizeof(struct file *);
81 	memcpy(nfdt->fd, ofdt->fd, cpy);
82 	memset((char *)nfdt->fd + cpy, 0, set);
83 
84 	copy_fd_bitmaps(nfdt, ofdt, ofdt->max_fds);
85 }
86 
87 static struct fdtable * alloc_fdtable(unsigned int nr)
88 {
89 	struct fdtable *fdt;
90 	void *data;
91 
92 	/*
93 	 * Figure out how many fds we actually want to support in this fdtable.
94 	 * Allocation steps are keyed to the size of the fdarray, since it
95 	 * grows far faster than any of the other dynamic data. We try to fit
96 	 * the fdarray into comfortable page-tuned chunks: starting at 1024B
97 	 * and growing in powers of two from there on.
98 	 */
99 	nr /= (1024 / sizeof(struct file *));
100 	nr = roundup_pow_of_two(nr + 1);
101 	nr *= (1024 / sizeof(struct file *));
102 	/*
103 	 * Note that this can drive nr *below* what we had passed if sysctl_nr_open
104 	 * had been set lower between the check in expand_files() and here.  Deal
105 	 * with that in caller, it's cheaper that way.
106 	 *
107 	 * We make sure that nr remains a multiple of BITS_PER_LONG - otherwise
108 	 * bitmaps handling below becomes unpleasant, to put it mildly...
109 	 */
110 	if (unlikely(nr > sysctl_nr_open))
111 		nr = ((sysctl_nr_open - 1) | (BITS_PER_LONG - 1)) + 1;
112 
113 	fdt = kmalloc(sizeof(struct fdtable), GFP_KERNEL_ACCOUNT);
114 	if (!fdt)
115 		goto out;
116 	fdt->max_fds = nr;
117 	data = kvmalloc_array(nr, sizeof(struct file *), GFP_KERNEL_ACCOUNT);
118 	if (!data)
119 		goto out_fdt;
120 	fdt->fd = data;
121 
122 	data = kvmalloc(max_t(size_t,
123 				 2 * nr / BITS_PER_BYTE + BITBIT_SIZE(nr), L1_CACHE_BYTES),
124 				 GFP_KERNEL_ACCOUNT);
125 	if (!data)
126 		goto out_arr;
127 	fdt->open_fds = data;
128 	data += nr / BITS_PER_BYTE;
129 	fdt->close_on_exec = data;
130 	data += nr / BITS_PER_BYTE;
131 	fdt->full_fds_bits = data;
132 
133 	return fdt;
134 
135 out_arr:
136 	kvfree(fdt->fd);
137 out_fdt:
138 	kfree(fdt);
139 out:
140 	return NULL;
141 }
142 
143 /*
144  * Expand the file descriptor table.
145  * This function will allocate a new fdtable and both fd array and fdset, of
146  * the given size.
147  * Return <0 error code on error; 1 on successful completion.
148  * The files->file_lock should be held on entry, and will be held on exit.
149  */
150 static int expand_fdtable(struct files_struct *files, unsigned int nr)
151 	__releases(files->file_lock)
152 	__acquires(files->file_lock)
153 {
154 	struct fdtable *new_fdt, *cur_fdt;
155 
156 	spin_unlock(&files->file_lock);
157 	new_fdt = alloc_fdtable(nr);
158 
159 	/* make sure all __fd_install() have seen resize_in_progress
160 	 * or have finished their rcu_read_lock_sched() section.
161 	 */
162 	if (atomic_read(&files->count) > 1)
163 		synchronize_rcu();
164 
165 	spin_lock(&files->file_lock);
166 	if (!new_fdt)
167 		return -ENOMEM;
168 	/*
169 	 * extremely unlikely race - sysctl_nr_open decreased between the check in
170 	 * caller and alloc_fdtable().  Cheaper to catch it here...
171 	 */
172 	if (unlikely(new_fdt->max_fds <= nr)) {
173 		__free_fdtable(new_fdt);
174 		return -EMFILE;
175 	}
176 	cur_fdt = files_fdtable(files);
177 	BUG_ON(nr < cur_fdt->max_fds);
178 	copy_fdtable(new_fdt, cur_fdt);
179 	rcu_assign_pointer(files->fdt, new_fdt);
180 	if (cur_fdt != &files->fdtab)
181 		call_rcu(&cur_fdt->rcu, free_fdtable_rcu);
182 	/* coupled with smp_rmb() in __fd_install() */
183 	smp_wmb();
184 	return 1;
185 }
186 
187 /*
188  * Expand files.
189  * This function will expand the file structures, if the requested size exceeds
190  * the current capacity and there is room for expansion.
191  * Return <0 error code on error; 0 when nothing done; 1 when files were
192  * expanded and execution may have blocked.
193  * The files->file_lock should be held on entry, and will be held on exit.
194  */
195 static int expand_files(struct files_struct *files, unsigned int nr)
196 	__releases(files->file_lock)
197 	__acquires(files->file_lock)
198 {
199 	struct fdtable *fdt;
200 	int expanded = 0;
201 
202 repeat:
203 	fdt = files_fdtable(files);
204 
205 	/* Do we need to expand? */
206 	if (nr < fdt->max_fds)
207 		return expanded;
208 
209 	/* Can we expand? */
210 	if (nr >= sysctl_nr_open)
211 		return -EMFILE;
212 
213 	if (unlikely(files->resize_in_progress)) {
214 		spin_unlock(&files->file_lock);
215 		expanded = 1;
216 		wait_event(files->resize_wait, !files->resize_in_progress);
217 		spin_lock(&files->file_lock);
218 		goto repeat;
219 	}
220 
221 	/* All good, so we try */
222 	files->resize_in_progress = true;
223 	expanded = expand_fdtable(files, nr);
224 	files->resize_in_progress = false;
225 
226 	wake_up_all(&files->resize_wait);
227 	return expanded;
228 }
229 
230 static inline void __set_close_on_exec(unsigned int fd, struct fdtable *fdt)
231 {
232 	__set_bit(fd, fdt->close_on_exec);
233 }
234 
235 static inline void __clear_close_on_exec(unsigned int fd, struct fdtable *fdt)
236 {
237 	if (test_bit(fd, fdt->close_on_exec))
238 		__clear_bit(fd, fdt->close_on_exec);
239 }
240 
241 static inline void __set_open_fd(unsigned int fd, struct fdtable *fdt)
242 {
243 	__set_bit(fd, fdt->open_fds);
244 	fd /= BITS_PER_LONG;
245 	if (!~fdt->open_fds[fd])
246 		__set_bit(fd, fdt->full_fds_bits);
247 }
248 
249 static inline void __clear_open_fd(unsigned int fd, struct fdtable *fdt)
250 {
251 	__clear_bit(fd, fdt->open_fds);
252 	__clear_bit(fd / BITS_PER_LONG, fdt->full_fds_bits);
253 }
254 
255 static unsigned int count_open_files(struct fdtable *fdt)
256 {
257 	unsigned int size = fdt->max_fds;
258 	unsigned int i;
259 
260 	/* Find the last open fd */
261 	for (i = size / BITS_PER_LONG; i > 0; ) {
262 		if (fdt->open_fds[--i])
263 			break;
264 	}
265 	i = (i + 1) * BITS_PER_LONG;
266 	return i;
267 }
268 
269 static unsigned int sane_fdtable_size(struct fdtable *fdt, unsigned int max_fds)
270 {
271 	unsigned int count;
272 
273 	count = count_open_files(fdt);
274 	if (max_fds < NR_OPEN_DEFAULT)
275 		max_fds = NR_OPEN_DEFAULT;
276 	return min(count, max_fds);
277 }
278 
279 /*
280  * Allocate a new files structure and copy contents from the
281  * passed in files structure.
282  * errorp will be valid only when the returned files_struct is NULL.
283  */
284 struct files_struct *dup_fd(struct files_struct *oldf, unsigned int max_fds, int *errorp)
285 {
286 	struct files_struct *newf;
287 	struct file **old_fds, **new_fds;
288 	unsigned int open_files, i;
289 	struct fdtable *old_fdt, *new_fdt;
290 
291 	*errorp = -ENOMEM;
292 	newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
293 	if (!newf)
294 		goto out;
295 
296 	atomic_set(&newf->count, 1);
297 
298 	spin_lock_init(&newf->file_lock);
299 	newf->resize_in_progress = false;
300 	init_waitqueue_head(&newf->resize_wait);
301 	newf->next_fd = 0;
302 	new_fdt = &newf->fdtab;
303 	new_fdt->max_fds = NR_OPEN_DEFAULT;
304 	new_fdt->close_on_exec = newf->close_on_exec_init;
305 	new_fdt->open_fds = newf->open_fds_init;
306 	new_fdt->full_fds_bits = newf->full_fds_bits_init;
307 	new_fdt->fd = &newf->fd_array[0];
308 
309 	spin_lock(&oldf->file_lock);
310 	old_fdt = files_fdtable(oldf);
311 	open_files = sane_fdtable_size(old_fdt, max_fds);
312 
313 	/*
314 	 * Check whether we need to allocate a larger fd array and fd set.
315 	 */
316 	while (unlikely(open_files > new_fdt->max_fds)) {
317 		spin_unlock(&oldf->file_lock);
318 
319 		if (new_fdt != &newf->fdtab)
320 			__free_fdtable(new_fdt);
321 
322 		new_fdt = alloc_fdtable(open_files - 1);
323 		if (!new_fdt) {
324 			*errorp = -ENOMEM;
325 			goto out_release;
326 		}
327 
328 		/* beyond sysctl_nr_open; nothing to do */
329 		if (unlikely(new_fdt->max_fds < open_files)) {
330 			__free_fdtable(new_fdt);
331 			*errorp = -EMFILE;
332 			goto out_release;
333 		}
334 
335 		/*
336 		 * Reacquire the oldf lock and a pointer to its fd table
337 		 * who knows it may have a new bigger fd table. We need
338 		 * the latest pointer.
339 		 */
340 		spin_lock(&oldf->file_lock);
341 		old_fdt = files_fdtable(oldf);
342 		open_files = sane_fdtable_size(old_fdt, max_fds);
343 	}
344 
345 	copy_fd_bitmaps(new_fdt, old_fdt, open_files);
346 
347 	old_fds = old_fdt->fd;
348 	new_fds = new_fdt->fd;
349 
350 	for (i = open_files; i != 0; i--) {
351 		struct file *f = *old_fds++;
352 		if (f) {
353 			get_file(f);
354 		} else {
355 			/*
356 			 * The fd may be claimed in the fd bitmap but not yet
357 			 * instantiated in the files array if a sibling thread
358 			 * is partway through open().  So make sure that this
359 			 * fd is available to the new process.
360 			 */
361 			__clear_open_fd(open_files - i, new_fdt);
362 		}
363 		rcu_assign_pointer(*new_fds++, f);
364 	}
365 	spin_unlock(&oldf->file_lock);
366 
367 	/* clear the remainder */
368 	memset(new_fds, 0, (new_fdt->max_fds - open_files) * sizeof(struct file *));
369 
370 	rcu_assign_pointer(newf->fdt, new_fdt);
371 
372 	return newf;
373 
374 out_release:
375 	kmem_cache_free(files_cachep, newf);
376 out:
377 	return NULL;
378 }
379 
380 static struct fdtable *close_files(struct files_struct * files)
381 {
382 	/*
383 	 * It is safe to dereference the fd table without RCU or
384 	 * ->file_lock because this is the last reference to the
385 	 * files structure.
386 	 */
387 	struct fdtable *fdt = rcu_dereference_raw(files->fdt);
388 	unsigned int i, j = 0;
389 
390 	for (;;) {
391 		unsigned long set;
392 		i = j * BITS_PER_LONG;
393 		if (i >= fdt->max_fds)
394 			break;
395 		set = fdt->open_fds[j++];
396 		while (set) {
397 			if (set & 1) {
398 				struct file * file = xchg(&fdt->fd[i], NULL);
399 				if (file) {
400 					filp_close(file, files);
401 					cond_resched();
402 				}
403 			}
404 			i++;
405 			set >>= 1;
406 		}
407 	}
408 
409 	return fdt;
410 }
411 
412 struct files_struct *get_files_struct(struct task_struct *task)
413 {
414 	struct files_struct *files;
415 
416 	task_lock(task);
417 	files = task->files;
418 	if (files)
419 		atomic_inc(&files->count);
420 	task_unlock(task);
421 
422 	return files;
423 }
424 
425 void put_files_struct(struct files_struct *files)
426 {
427 	if (atomic_dec_and_test(&files->count)) {
428 		struct fdtable *fdt = close_files(files);
429 
430 		/* free the arrays if they are not embedded */
431 		if (fdt != &files->fdtab)
432 			__free_fdtable(fdt);
433 		kmem_cache_free(files_cachep, files);
434 	}
435 }
436 
437 void reset_files_struct(struct files_struct *files)
438 {
439 	struct task_struct *tsk = current;
440 	struct files_struct *old;
441 
442 	old = tsk->files;
443 	task_lock(tsk);
444 	tsk->files = files;
445 	task_unlock(tsk);
446 	put_files_struct(old);
447 }
448 
449 void exit_files(struct task_struct *tsk)
450 {
451 	struct files_struct * files = tsk->files;
452 
453 	if (files) {
454 		task_lock(tsk);
455 		tsk->files = NULL;
456 		task_unlock(tsk);
457 		put_files_struct(files);
458 	}
459 }
460 
461 struct files_struct init_files = {
462 	.count		= ATOMIC_INIT(1),
463 	.fdt		= &init_files.fdtab,
464 	.fdtab		= {
465 		.max_fds	= NR_OPEN_DEFAULT,
466 		.fd		= &init_files.fd_array[0],
467 		.close_on_exec	= init_files.close_on_exec_init,
468 		.open_fds	= init_files.open_fds_init,
469 		.full_fds_bits	= init_files.full_fds_bits_init,
470 	},
471 	.file_lock	= __SPIN_LOCK_UNLOCKED(init_files.file_lock),
472 	.resize_wait	= __WAIT_QUEUE_HEAD_INITIALIZER(init_files.resize_wait),
473 };
474 
475 static unsigned int find_next_fd(struct fdtable *fdt, unsigned int start)
476 {
477 	unsigned int maxfd = fdt->max_fds;
478 	unsigned int maxbit = maxfd / BITS_PER_LONG;
479 	unsigned int bitbit = start / BITS_PER_LONG;
480 
481 	bitbit = find_next_zero_bit(fdt->full_fds_bits, maxbit, bitbit) * BITS_PER_LONG;
482 	if (bitbit > maxfd)
483 		return maxfd;
484 	if (bitbit > start)
485 		start = bitbit;
486 	return find_next_zero_bit(fdt->open_fds, maxfd, start);
487 }
488 
489 /*
490  * allocate a file descriptor, mark it busy.
491  */
492 int __alloc_fd(struct files_struct *files,
493 	       unsigned start, unsigned end, unsigned flags)
494 {
495 	unsigned int fd;
496 	int error;
497 	struct fdtable *fdt;
498 
499 	spin_lock(&files->file_lock);
500 repeat:
501 	fdt = files_fdtable(files);
502 	fd = start;
503 	if (fd < files->next_fd)
504 		fd = files->next_fd;
505 
506 	if (fd < fdt->max_fds)
507 		fd = find_next_fd(fdt, fd);
508 
509 	/*
510 	 * N.B. For clone tasks sharing a files structure, this test
511 	 * will limit the total number of files that can be opened.
512 	 */
513 	error = -EMFILE;
514 	if (fd >= end)
515 		goto out;
516 
517 	error = expand_files(files, fd);
518 	if (error < 0)
519 		goto out;
520 
521 	/*
522 	 * If we needed to expand the fs array we
523 	 * might have blocked - try again.
524 	 */
525 	if (error)
526 		goto repeat;
527 
528 	if (start <= files->next_fd)
529 		files->next_fd = fd + 1;
530 
531 	__set_open_fd(fd, fdt);
532 	if (flags & O_CLOEXEC)
533 		__set_close_on_exec(fd, fdt);
534 	else
535 		__clear_close_on_exec(fd, fdt);
536 	error = fd;
537 #if 1
538 	/* Sanity check */
539 	if (rcu_access_pointer(fdt->fd[fd]) != NULL) {
540 		printk(KERN_WARNING "alloc_fd: slot %d not NULL!\n", fd);
541 		rcu_assign_pointer(fdt->fd[fd], NULL);
542 	}
543 #endif
544 
545 out:
546 	spin_unlock(&files->file_lock);
547 	return error;
548 }
549 
550 static int alloc_fd(unsigned start, unsigned flags)
551 {
552 	return __alloc_fd(current->files, start, rlimit(RLIMIT_NOFILE), flags);
553 }
554 
555 int __get_unused_fd_flags(unsigned flags, unsigned long nofile)
556 {
557 	return __alloc_fd(current->files, 0, nofile, flags);
558 }
559 
560 int get_unused_fd_flags(unsigned flags)
561 {
562 	return __get_unused_fd_flags(flags, rlimit(RLIMIT_NOFILE));
563 }
564 EXPORT_SYMBOL(get_unused_fd_flags);
565 
566 static void __put_unused_fd(struct files_struct *files, unsigned int fd)
567 {
568 	struct fdtable *fdt = files_fdtable(files);
569 	__clear_open_fd(fd, fdt);
570 	if (fd < files->next_fd)
571 		files->next_fd = fd;
572 }
573 
574 void put_unused_fd(unsigned int fd)
575 {
576 	struct files_struct *files = current->files;
577 	spin_lock(&files->file_lock);
578 	__put_unused_fd(files, fd);
579 	spin_unlock(&files->file_lock);
580 }
581 
582 EXPORT_SYMBOL(put_unused_fd);
583 
584 /*
585  * Install a file pointer in the fd array.
586  *
587  * The VFS is full of places where we drop the files lock between
588  * setting the open_fds bitmap and installing the file in the file
589  * array.  At any such point, we are vulnerable to a dup2() race
590  * installing a file in the array before us.  We need to detect this and
591  * fput() the struct file we are about to overwrite in this case.
592  *
593  * It should never happen - if we allow dup2() do it, _really_ bad things
594  * will follow.
595  *
596  * NOTE: __fd_install() variant is really, really low-level; don't
597  * use it unless you are forced to by truly lousy API shoved down
598  * your throat.  'files' *MUST* be either current->files or obtained
599  * by get_files_struct(current) done by whoever had given it to you,
600  * or really bad things will happen.  Normally you want to use
601  * fd_install() instead.
602  */
603 
604 void __fd_install(struct files_struct *files, unsigned int fd,
605 		struct file *file)
606 {
607 	struct fdtable *fdt;
608 
609 	rcu_read_lock_sched();
610 
611 	if (unlikely(files->resize_in_progress)) {
612 		rcu_read_unlock_sched();
613 		spin_lock(&files->file_lock);
614 		fdt = files_fdtable(files);
615 		BUG_ON(fdt->fd[fd] != NULL);
616 		rcu_assign_pointer(fdt->fd[fd], file);
617 		spin_unlock(&files->file_lock);
618 		return;
619 	}
620 	/* coupled with smp_wmb() in expand_fdtable() */
621 	smp_rmb();
622 	fdt = rcu_dereference_sched(files->fdt);
623 	BUG_ON(fdt->fd[fd] != NULL);
624 	rcu_assign_pointer(fdt->fd[fd], file);
625 	rcu_read_unlock_sched();
626 }
627 
628 void fd_install(unsigned int fd, struct file *file)
629 {
630 	__fd_install(current->files, fd, file);
631 }
632 
633 EXPORT_SYMBOL(fd_install);
634 
635 static struct file *pick_file(struct files_struct *files, unsigned fd)
636 {
637 	struct file *file = NULL;
638 	struct fdtable *fdt;
639 
640 	spin_lock(&files->file_lock);
641 	fdt = files_fdtable(files);
642 	if (fd >= fdt->max_fds)
643 		goto out_unlock;
644 	file = fdt->fd[fd];
645 	if (!file)
646 		goto out_unlock;
647 	rcu_assign_pointer(fdt->fd[fd], NULL);
648 	__put_unused_fd(files, fd);
649 
650 out_unlock:
651 	spin_unlock(&files->file_lock);
652 	return file;
653 }
654 
655 /*
656  * The same warnings as for __alloc_fd()/__fd_install() apply here...
657  */
658 int __close_fd(struct files_struct *files, unsigned fd)
659 {
660 	struct file *file;
661 
662 	file = pick_file(files, fd);
663 	if (!file)
664 		return -EBADF;
665 
666 	return filp_close(file, files);
667 }
668 EXPORT_SYMBOL(__close_fd); /* for ksys_close() */
669 
670 /**
671  * __close_range() - Close all file descriptors in a given range.
672  *
673  * @fd:     starting file descriptor to close
674  * @max_fd: last file descriptor to close
675  *
676  * This closes a range of file descriptors. All file descriptors
677  * from @fd up to and including @max_fd are closed.
678  */
679 int __close_range(unsigned fd, unsigned max_fd, unsigned int flags)
680 {
681 	unsigned int cur_max;
682 	struct task_struct *me = current;
683 	struct files_struct *cur_fds = me->files, *fds = NULL;
684 
685 	if (flags & ~CLOSE_RANGE_UNSHARE)
686 		return -EINVAL;
687 
688 	if (fd > max_fd)
689 		return -EINVAL;
690 
691 	rcu_read_lock();
692 	cur_max = files_fdtable(cur_fds)->max_fds;
693 	rcu_read_unlock();
694 
695 	/* cap to last valid index into fdtable */
696 	cur_max--;
697 
698 	if (flags & CLOSE_RANGE_UNSHARE) {
699 		int ret;
700 		unsigned int max_unshare_fds = NR_OPEN_MAX;
701 
702 		/*
703 		 * If the requested range is greater than the current maximum,
704 		 * we're closing everything so only copy all file descriptors
705 		 * beneath the lowest file descriptor.
706 		 */
707 		if (max_fd >= cur_max)
708 			max_unshare_fds = fd;
709 
710 		ret = unshare_fd(CLONE_FILES, max_unshare_fds, &fds);
711 		if (ret)
712 			return ret;
713 
714 		/*
715 		 * We used to share our file descriptor table, and have now
716 		 * created a private one, make sure we're using it below.
717 		 */
718 		if (fds)
719 			swap(cur_fds, fds);
720 	}
721 
722 	max_fd = min(max_fd, cur_max);
723 	while (fd <= max_fd) {
724 		struct file *file;
725 
726 		file = pick_file(cur_fds, fd++);
727 		if (!file)
728 			continue;
729 
730 		filp_close(file, cur_fds);
731 		cond_resched();
732 	}
733 
734 	if (fds) {
735 		/*
736 		 * We're done closing the files we were supposed to. Time to install
737 		 * the new file descriptor table and drop the old one.
738 		 */
739 		task_lock(me);
740 		me->files = cur_fds;
741 		task_unlock(me);
742 		put_files_struct(fds);
743 	}
744 
745 	return 0;
746 }
747 
748 /*
749  * variant of __close_fd that gets a ref on the file for later fput.
750  * The caller must ensure that filp_close() called on the file, and then
751  * an fput().
752  */
753 int __close_fd_get_file(unsigned int fd, struct file **res)
754 {
755 	struct files_struct *files = current->files;
756 	struct file *file;
757 	struct fdtable *fdt;
758 
759 	spin_lock(&files->file_lock);
760 	fdt = files_fdtable(files);
761 	if (fd >= fdt->max_fds)
762 		goto out_unlock;
763 	file = fdt->fd[fd];
764 	if (!file)
765 		goto out_unlock;
766 	rcu_assign_pointer(fdt->fd[fd], NULL);
767 	__put_unused_fd(files, fd);
768 	spin_unlock(&files->file_lock);
769 	get_file(file);
770 	*res = file;
771 	return 0;
772 
773 out_unlock:
774 	spin_unlock(&files->file_lock);
775 	*res = NULL;
776 	return -ENOENT;
777 }
778 
779 void do_close_on_exec(struct files_struct *files)
780 {
781 	unsigned i;
782 	struct fdtable *fdt;
783 
784 	/* exec unshares first */
785 	spin_lock(&files->file_lock);
786 	for (i = 0; ; i++) {
787 		unsigned long set;
788 		unsigned fd = i * BITS_PER_LONG;
789 		fdt = files_fdtable(files);
790 		if (fd >= fdt->max_fds)
791 			break;
792 		set = fdt->close_on_exec[i];
793 		if (!set)
794 			continue;
795 		fdt->close_on_exec[i] = 0;
796 		for ( ; set ; fd++, set >>= 1) {
797 			struct file *file;
798 			if (!(set & 1))
799 				continue;
800 			file = fdt->fd[fd];
801 			if (!file)
802 				continue;
803 			rcu_assign_pointer(fdt->fd[fd], NULL);
804 			__put_unused_fd(files, fd);
805 			spin_unlock(&files->file_lock);
806 			filp_close(file, files);
807 			cond_resched();
808 			spin_lock(&files->file_lock);
809 		}
810 
811 	}
812 	spin_unlock(&files->file_lock);
813 }
814 
815 static struct file *__fget_files(struct files_struct *files, unsigned int fd,
816 				 fmode_t mask, unsigned int refs)
817 {
818 	struct file *file;
819 
820 	rcu_read_lock();
821 loop:
822 	file = fcheck_files(files, fd);
823 	if (file) {
824 		/* File object ref couldn't be taken.
825 		 * dup2() atomicity guarantee is the reason
826 		 * we loop to catch the new file (or NULL pointer)
827 		 */
828 		if (file->f_mode & mask)
829 			file = NULL;
830 		else if (!get_file_rcu_many(file, refs))
831 			goto loop;
832 	}
833 	rcu_read_unlock();
834 
835 	return file;
836 }
837 
838 static inline struct file *__fget(unsigned int fd, fmode_t mask,
839 				  unsigned int refs)
840 {
841 	return __fget_files(current->files, fd, mask, refs);
842 }
843 
844 struct file *fget_many(unsigned int fd, unsigned int refs)
845 {
846 	return __fget(fd, FMODE_PATH, refs);
847 }
848 
849 struct file *fget(unsigned int fd)
850 {
851 	return __fget(fd, FMODE_PATH, 1);
852 }
853 EXPORT_SYMBOL(fget);
854 
855 struct file *fget_raw(unsigned int fd)
856 {
857 	return __fget(fd, 0, 1);
858 }
859 EXPORT_SYMBOL(fget_raw);
860 
861 struct file *fget_task(struct task_struct *task, unsigned int fd)
862 {
863 	struct file *file = NULL;
864 
865 	task_lock(task);
866 	if (task->files)
867 		file = __fget_files(task->files, fd, 0, 1);
868 	task_unlock(task);
869 
870 	return file;
871 }
872 
873 /*
874  * Lightweight file lookup - no refcnt increment if fd table isn't shared.
875  *
876  * You can use this instead of fget if you satisfy all of the following
877  * conditions:
878  * 1) You must call fput_light before exiting the syscall and returning control
879  *    to userspace (i.e. you cannot remember the returned struct file * after
880  *    returning to userspace).
881  * 2) You must not call filp_close on the returned struct file * in between
882  *    calls to fget_light and fput_light.
883  * 3) You must not clone the current task in between the calls to fget_light
884  *    and fput_light.
885  *
886  * The fput_needed flag returned by fget_light should be passed to the
887  * corresponding fput_light.
888  */
889 static unsigned long __fget_light(unsigned int fd, fmode_t mask)
890 {
891 	struct files_struct *files = current->files;
892 	struct file *file;
893 
894 	if (atomic_read(&files->count) == 1) {
895 		file = __fcheck_files(files, fd);
896 		if (!file || unlikely(file->f_mode & mask))
897 			return 0;
898 		return (unsigned long)file;
899 	} else {
900 		file = __fget(fd, mask, 1);
901 		if (!file)
902 			return 0;
903 		return FDPUT_FPUT | (unsigned long)file;
904 	}
905 }
906 unsigned long __fdget(unsigned int fd)
907 {
908 	return __fget_light(fd, FMODE_PATH);
909 }
910 EXPORT_SYMBOL(__fdget);
911 
912 unsigned long __fdget_raw(unsigned int fd)
913 {
914 	return __fget_light(fd, 0);
915 }
916 
917 unsigned long __fdget_pos(unsigned int fd)
918 {
919 	unsigned long v = __fdget(fd);
920 	struct file *file = (struct file *)(v & ~3);
921 
922 	if (file && (file->f_mode & FMODE_ATOMIC_POS)) {
923 		if (file_count(file) > 1) {
924 			v |= FDPUT_POS_UNLOCK;
925 			mutex_lock(&file->f_pos_lock);
926 		}
927 	}
928 	return v;
929 }
930 
931 void __f_unlock_pos(struct file *f)
932 {
933 	mutex_unlock(&f->f_pos_lock);
934 }
935 
936 /*
937  * We only lock f_pos if we have threads or if the file might be
938  * shared with another process. In both cases we'll have an elevated
939  * file count (done either by fdget() or by fork()).
940  */
941 
942 void set_close_on_exec(unsigned int fd, int flag)
943 {
944 	struct files_struct *files = current->files;
945 	struct fdtable *fdt;
946 	spin_lock(&files->file_lock);
947 	fdt = files_fdtable(files);
948 	if (flag)
949 		__set_close_on_exec(fd, fdt);
950 	else
951 		__clear_close_on_exec(fd, fdt);
952 	spin_unlock(&files->file_lock);
953 }
954 
955 bool get_close_on_exec(unsigned int fd)
956 {
957 	struct files_struct *files = current->files;
958 	struct fdtable *fdt;
959 	bool res;
960 	rcu_read_lock();
961 	fdt = files_fdtable(files);
962 	res = close_on_exec(fd, fdt);
963 	rcu_read_unlock();
964 	return res;
965 }
966 
967 static int do_dup2(struct files_struct *files,
968 	struct file *file, unsigned fd, unsigned flags)
969 __releases(&files->file_lock)
970 {
971 	struct file *tofree;
972 	struct fdtable *fdt;
973 
974 	/*
975 	 * We need to detect attempts to do dup2() over allocated but still
976 	 * not finished descriptor.  NB: OpenBSD avoids that at the price of
977 	 * extra work in their equivalent of fget() - they insert struct
978 	 * file immediately after grabbing descriptor, mark it larval if
979 	 * more work (e.g. actual opening) is needed and make sure that
980 	 * fget() treats larval files as absent.  Potentially interesting,
981 	 * but while extra work in fget() is trivial, locking implications
982 	 * and amount of surgery on open()-related paths in VFS are not.
983 	 * FreeBSD fails with -EBADF in the same situation, NetBSD "solution"
984 	 * deadlocks in rather amusing ways, AFAICS.  All of that is out of
985 	 * scope of POSIX or SUS, since neither considers shared descriptor
986 	 * tables and this condition does not arise without those.
987 	 */
988 	fdt = files_fdtable(files);
989 	tofree = fdt->fd[fd];
990 	if (!tofree && fd_is_open(fd, fdt))
991 		goto Ebusy;
992 	get_file(file);
993 	rcu_assign_pointer(fdt->fd[fd], file);
994 	__set_open_fd(fd, fdt);
995 	if (flags & O_CLOEXEC)
996 		__set_close_on_exec(fd, fdt);
997 	else
998 		__clear_close_on_exec(fd, fdt);
999 	spin_unlock(&files->file_lock);
1000 
1001 	if (tofree)
1002 		filp_close(tofree, files);
1003 
1004 	return fd;
1005 
1006 Ebusy:
1007 	spin_unlock(&files->file_lock);
1008 	return -EBUSY;
1009 }
1010 
1011 int replace_fd(unsigned fd, struct file *file, unsigned flags)
1012 {
1013 	int err;
1014 	struct files_struct *files = current->files;
1015 
1016 	if (!file)
1017 		return __close_fd(files, fd);
1018 
1019 	if (fd >= rlimit(RLIMIT_NOFILE))
1020 		return -EBADF;
1021 
1022 	spin_lock(&files->file_lock);
1023 	err = expand_files(files, fd);
1024 	if (unlikely(err < 0))
1025 		goto out_unlock;
1026 	return do_dup2(files, file, fd, flags);
1027 
1028 out_unlock:
1029 	spin_unlock(&files->file_lock);
1030 	return err;
1031 }
1032 
1033 static int ksys_dup3(unsigned int oldfd, unsigned int newfd, int flags)
1034 {
1035 	int err = -EBADF;
1036 	struct file *file;
1037 	struct files_struct *files = current->files;
1038 
1039 	if ((flags & ~O_CLOEXEC) != 0)
1040 		return -EINVAL;
1041 
1042 	if (unlikely(oldfd == newfd))
1043 		return -EINVAL;
1044 
1045 	if (newfd >= rlimit(RLIMIT_NOFILE))
1046 		return -EBADF;
1047 
1048 	spin_lock(&files->file_lock);
1049 	err = expand_files(files, newfd);
1050 	file = fcheck(oldfd);
1051 	if (unlikely(!file))
1052 		goto Ebadf;
1053 	if (unlikely(err < 0)) {
1054 		if (err == -EMFILE)
1055 			goto Ebadf;
1056 		goto out_unlock;
1057 	}
1058 	return do_dup2(files, file, newfd, flags);
1059 
1060 Ebadf:
1061 	err = -EBADF;
1062 out_unlock:
1063 	spin_unlock(&files->file_lock);
1064 	return err;
1065 }
1066 
1067 SYSCALL_DEFINE3(dup3, unsigned int, oldfd, unsigned int, newfd, int, flags)
1068 {
1069 	return ksys_dup3(oldfd, newfd, flags);
1070 }
1071 
1072 SYSCALL_DEFINE2(dup2, unsigned int, oldfd, unsigned int, newfd)
1073 {
1074 	if (unlikely(newfd == oldfd)) { /* corner case */
1075 		struct files_struct *files = current->files;
1076 		int retval = oldfd;
1077 
1078 		rcu_read_lock();
1079 		if (!fcheck_files(files, oldfd))
1080 			retval = -EBADF;
1081 		rcu_read_unlock();
1082 		return retval;
1083 	}
1084 	return ksys_dup3(oldfd, newfd, 0);
1085 }
1086 
1087 int ksys_dup(unsigned int fildes)
1088 {
1089 	int ret = -EBADF;
1090 	struct file *file = fget_raw(fildes);
1091 
1092 	if (file) {
1093 		ret = get_unused_fd_flags(0);
1094 		if (ret >= 0)
1095 			fd_install(ret, file);
1096 		else
1097 			fput(file);
1098 	}
1099 	return ret;
1100 }
1101 
1102 SYSCALL_DEFINE1(dup, unsigned int, fildes)
1103 {
1104 	return ksys_dup(fildes);
1105 }
1106 
1107 int f_dupfd(unsigned int from, struct file *file, unsigned flags)
1108 {
1109 	int err;
1110 	if (from >= rlimit(RLIMIT_NOFILE))
1111 		return -EINVAL;
1112 	err = alloc_fd(from, flags);
1113 	if (err >= 0) {
1114 		get_file(file);
1115 		fd_install(err, file);
1116 	}
1117 	return err;
1118 }
1119 
1120 int iterate_fd(struct files_struct *files, unsigned n,
1121 		int (*f)(const void *, struct file *, unsigned),
1122 		const void *p)
1123 {
1124 	struct fdtable *fdt;
1125 	int res = 0;
1126 	if (!files)
1127 		return 0;
1128 	spin_lock(&files->file_lock);
1129 	for (fdt = files_fdtable(files); n < fdt->max_fds; n++) {
1130 		struct file *file;
1131 		file = rcu_dereference_check_fdtable(files, fdt->fd[n]);
1132 		if (!file)
1133 			continue;
1134 		res = f(p, file, n);
1135 		if (res)
1136 			break;
1137 	}
1138 	spin_unlock(&files->file_lock);
1139 	return res;
1140 }
1141 EXPORT_SYMBOL(iterate_fd);
1142