xref: /linux/fs/file.c (revision 00b04f4495c354cad82f96d41947aa70f71e2cc4)
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 #include <linux/file_ref.h>
24 #include <net/sock.h>
25 #include <linux/init_task.h>
26 
27 #include "internal.h"
28 
29 static noinline bool __file_ref_put_badval(file_ref_t *ref, unsigned long cnt)
30 {
31 	/*
32 	 * If the reference count was already in the dead zone, then this
33 	 * put() operation is imbalanced. Warn, put the reference count back to
34 	 * DEAD and tell the caller to not deconstruct the object.
35 	 */
36 	if (WARN_ONCE(cnt >= FILE_REF_RELEASED, "imbalanced put on file reference count")) {
37 		atomic_long_set(&ref->refcnt, FILE_REF_DEAD);
38 		return false;
39 	}
40 
41 	/*
42 	 * This is a put() operation on a saturated refcount. Restore the
43 	 * mean saturation value and tell the caller to not deconstruct the
44 	 * object.
45 	 */
46 	if (cnt > FILE_REF_MAXREF)
47 		atomic_long_set(&ref->refcnt, FILE_REF_SATURATED);
48 	return false;
49 }
50 
51 /**
52  * __file_ref_put - Slowpath of file_ref_put()
53  * @ref:	Pointer to the reference count
54  * @cnt:	Current reference count
55  *
56  * Invoked when the reference count is outside of the valid zone.
57  *
58  * Return:
59  *	True if this was the last reference with no future references
60  *	possible. This signals the caller that it can safely schedule the
61  *	object, which is protected by the reference counter, for
62  *	deconstruction.
63  *
64  *	False if there are still active references or the put() raced
65  *	with a concurrent get()/put() pair. Caller is not allowed to
66  *	deconstruct the protected object.
67  */
68 bool __file_ref_put(file_ref_t *ref, unsigned long cnt)
69 {
70 	/* Did this drop the last reference? */
71 	if (likely(cnt == FILE_REF_NOREF)) {
72 		/*
73 		 * Carefully try to set the reference count to FILE_REF_DEAD.
74 		 *
75 		 * This can fail if a concurrent get() operation has
76 		 * elevated it again or the corresponding put() even marked
77 		 * it dead already. Both are valid situations and do not
78 		 * require a retry. If this fails the caller is not
79 		 * allowed to deconstruct the object.
80 		 */
81 		if (!atomic_long_try_cmpxchg_release(&ref->refcnt, &cnt, FILE_REF_DEAD))
82 			return false;
83 
84 		/*
85 		 * The caller can safely schedule the object for
86 		 * deconstruction. Provide acquire ordering.
87 		 */
88 		smp_acquire__after_ctrl_dep();
89 		return true;
90 	}
91 
92 	return __file_ref_put_badval(ref, cnt);
93 }
94 EXPORT_SYMBOL_GPL(__file_ref_put);
95 
96 unsigned int sysctl_nr_open __read_mostly = 1024*1024;
97 unsigned int sysctl_nr_open_min = BITS_PER_LONG;
98 /* our min() is unusable in constant expressions ;-/ */
99 #define __const_min(x, y) ((x) < (y) ? (x) : (y))
100 unsigned int sysctl_nr_open_max =
101 	__const_min(INT_MAX, ~(size_t)0/sizeof(void *)) & -BITS_PER_LONG;
102 
103 static void __free_fdtable(struct fdtable *fdt)
104 {
105 	kvfree(fdt->fd);
106 	kvfree(fdt->open_fds);
107 	kfree(fdt);
108 }
109 
110 static void free_fdtable_rcu(struct rcu_head *rcu)
111 {
112 	__free_fdtable(container_of(rcu, struct fdtable, rcu));
113 }
114 
115 #define BITBIT_NR(nr)	BITS_TO_LONGS(BITS_TO_LONGS(nr))
116 #define BITBIT_SIZE(nr)	(BITBIT_NR(nr) * sizeof(long))
117 
118 #define fdt_words(fdt) ((fdt)->max_fds / BITS_PER_LONG) // words in ->open_fds
119 /*
120  * Copy 'count' fd bits from the old table to the new table and clear the extra
121  * space if any.  This does not copy the file pointers.  Called with the files
122  * spinlock held for write.
123  */
124 static inline void copy_fd_bitmaps(struct fdtable *nfdt, struct fdtable *ofdt,
125 			    unsigned int copy_words)
126 {
127 	unsigned int nwords = fdt_words(nfdt);
128 
129 	bitmap_copy_and_extend(nfdt->open_fds, ofdt->open_fds,
130 			copy_words * BITS_PER_LONG, nwords * BITS_PER_LONG);
131 	bitmap_copy_and_extend(nfdt->close_on_exec, ofdt->close_on_exec,
132 			copy_words * BITS_PER_LONG, nwords * BITS_PER_LONG);
133 	bitmap_copy_and_extend(nfdt->full_fds_bits, ofdt->full_fds_bits,
134 			copy_words, nwords);
135 }
136 
137 /*
138  * Copy all file descriptors from the old table to the new, expanded table and
139  * clear the extra space.  Called with the files spinlock held for write.
140  */
141 static void copy_fdtable(struct fdtable *nfdt, struct fdtable *ofdt)
142 {
143 	size_t cpy, set;
144 
145 	BUG_ON(nfdt->max_fds < ofdt->max_fds);
146 
147 	cpy = ofdt->max_fds * sizeof(struct file *);
148 	set = (nfdt->max_fds - ofdt->max_fds) * sizeof(struct file *);
149 	memcpy(nfdt->fd, ofdt->fd, cpy);
150 	memset((char *)nfdt->fd + cpy, 0, set);
151 
152 	copy_fd_bitmaps(nfdt, ofdt, fdt_words(ofdt));
153 }
154 
155 /*
156  * Note how the fdtable bitmap allocations very much have to be a multiple of
157  * BITS_PER_LONG. This is not only because we walk those things in chunks of
158  * 'unsigned long' in some places, but simply because that is how the Linux
159  * kernel bitmaps are defined to work: they are not "bits in an array of bytes",
160  * they are very much "bits in an array of unsigned long".
161  */
162 static struct fdtable *alloc_fdtable(unsigned int slots_wanted)
163 {
164 	struct fdtable *fdt;
165 	unsigned int nr;
166 	void *data;
167 
168 	/*
169 	 * Figure out how many fds we actually want to support in this fdtable.
170 	 * Allocation steps are keyed to the size of the fdarray, since it
171 	 * grows far faster than any of the other dynamic data. We try to fit
172 	 * the fdarray into comfortable page-tuned chunks: starting at 1024B
173 	 * and growing in powers of two from there on.  Since we called only
174 	 * with slots_wanted > BITS_PER_LONG (embedded instance in files->fdtab
175 	 * already gives BITS_PER_LONG slots), the above boils down to
176 	 * 1.  use the smallest power of two large enough to give us that many
177 	 * slots.
178 	 * 2.  on 32bit skip 64 and 128 - the minimal capacity we want there is
179 	 * 256 slots (i.e. 1Kb fd array).
180 	 * 3.  on 64bit don't skip anything, 1Kb fd array means 128 slots there
181 	 * and we are never going to be asked for 64 or less.
182 	 */
183 	if (IS_ENABLED(CONFIG_32BIT) && slots_wanted < 256)
184 		nr = 256;
185 	else
186 		nr = roundup_pow_of_two(slots_wanted);
187 	/*
188 	 * Note that this can drive nr *below* what we had passed if sysctl_nr_open
189 	 * had been set lower between the check in expand_files() and here.
190 	 *
191 	 * We make sure that nr remains a multiple of BITS_PER_LONG - otherwise
192 	 * bitmaps handling below becomes unpleasant, to put it mildly...
193 	 */
194 	if (unlikely(nr > sysctl_nr_open)) {
195 		nr = round_down(sysctl_nr_open, BITS_PER_LONG);
196 		if (nr < slots_wanted)
197 			return ERR_PTR(-EMFILE);
198 	}
199 
200 	/*
201 	 * Check if the allocation size would exceed INT_MAX. kvmalloc_array()
202 	 * and kvmalloc() will warn if the allocation size is greater than
203 	 * INT_MAX, as filp_cache objects are not __GFP_NOWARN.
204 	 *
205 	 * This can happen when sysctl_nr_open is set to a very high value and
206 	 * a process tries to use a file descriptor near that limit. For example,
207 	 * if sysctl_nr_open is set to 1073741816 (0x3ffffff8) - which is what
208 	 * systemd typically sets it to - then trying to use a file descriptor
209 	 * close to that value will require allocating a file descriptor table
210 	 * that exceeds 8GB in size.
211 	 */
212 	if (unlikely(nr > INT_MAX / sizeof(struct file *)))
213 		return ERR_PTR(-EMFILE);
214 
215 	fdt = kmalloc_obj(struct fdtable, GFP_KERNEL_ACCOUNT);
216 	if (!fdt)
217 		goto out;
218 	fdt->max_fds = nr;
219 	data = kvmalloc_objs(struct file *, nr, GFP_KERNEL_ACCOUNT);
220 	if (!data)
221 		goto out_fdt;
222 	fdt->fd = data;
223 
224 	data = kvmalloc(max_t(size_t,
225 				 2 * nr / BITS_PER_BYTE + BITBIT_SIZE(nr), L1_CACHE_BYTES),
226 				 GFP_KERNEL_ACCOUNT);
227 	if (!data)
228 		goto out_arr;
229 	fdt->open_fds = data;
230 	data += nr / BITS_PER_BYTE;
231 	fdt->close_on_exec = data;
232 	data += nr / BITS_PER_BYTE;
233 	fdt->full_fds_bits = data;
234 
235 	return fdt;
236 
237 out_arr:
238 	kvfree(fdt->fd);
239 out_fdt:
240 	kfree(fdt);
241 out:
242 	return ERR_PTR(-ENOMEM);
243 }
244 
245 /*
246  * Expand the file descriptor table.
247  * This function will allocate a new fdtable and both fd array and fdset, of
248  * the given size.
249  * Return <0 error code on error; 0 on successful completion.
250  * The files->file_lock should be held on entry, and will be held on exit.
251  */
252 static int expand_fdtable(struct files_struct *files, unsigned int nr)
253 	__releases(files->file_lock)
254 	__acquires(files->file_lock)
255 {
256 	struct fdtable *new_fdt, *cur_fdt;
257 
258 	spin_unlock(&files->file_lock);
259 	new_fdt = alloc_fdtable(nr + 1);
260 
261 	/* make sure all fd_install() have seen resize_in_progress
262 	 * or have finished their rcu_read_lock_sched() section.
263 	 */
264 	if (atomic_read(&files->count) > 1)
265 		synchronize_rcu();
266 
267 	spin_lock(&files->file_lock);
268 	if (IS_ERR(new_fdt))
269 		return PTR_ERR(new_fdt);
270 	cur_fdt = files_fdtable(files);
271 	BUG_ON(nr < cur_fdt->max_fds);
272 	copy_fdtable(new_fdt, cur_fdt);
273 	rcu_assign_pointer(files->fdt, new_fdt);
274 	if (cur_fdt != &files->fdtab)
275 		call_rcu(&cur_fdt->rcu, free_fdtable_rcu);
276 	/* coupled with smp_rmb() in fd_install() */
277 	smp_wmb();
278 	return 0;
279 }
280 
281 /*
282  * Expand files.
283  * This function will expand the file structures, if the requested size exceeds
284  * the current capacity and there is room for expansion.
285  * Return <0 error code on error; 0 on success.
286  * The files->file_lock should be held on entry, and will be held on exit.
287  */
288 static int expand_files(struct files_struct *files, unsigned int nr)
289 	__releases(files->file_lock)
290 	__acquires(files->file_lock)
291 {
292 	struct fdtable *fdt;
293 	int error;
294 
295 repeat:
296 	fdt = files_fdtable(files);
297 
298 	/* Do we need to expand? */
299 	if (nr < fdt->max_fds)
300 		return 0;
301 
302 	if (unlikely(files->resize_in_progress)) {
303 		spin_unlock(&files->file_lock);
304 		wait_event(files->resize_wait, !files->resize_in_progress);
305 		spin_lock(&files->file_lock);
306 		goto repeat;
307 	}
308 
309 	/* Can we expand? */
310 	if (unlikely(nr >= sysctl_nr_open))
311 		return -EMFILE;
312 
313 	/* All good, so we try */
314 	files->resize_in_progress = true;
315 	error = expand_fdtable(files, nr);
316 	files->resize_in_progress = false;
317 
318 	wake_up_all(&files->resize_wait);
319 	return error;
320 }
321 
322 static inline void __set_close_on_exec(unsigned int fd, struct fdtable *fdt,
323 				       bool set)
324 {
325 	if (set) {
326 		__set_bit(fd, fdt->close_on_exec);
327 	} else {
328 		if (test_bit(fd, fdt->close_on_exec))
329 			__clear_bit(fd, fdt->close_on_exec);
330 	}
331 }
332 
333 static inline void __set_open_fd(unsigned int fd, struct fdtable *fdt, bool set)
334 {
335 	__set_bit(fd, fdt->open_fds);
336 	__set_close_on_exec(fd, fdt, set);
337 	fd /= BITS_PER_LONG;
338 	if (!~fdt->open_fds[fd])
339 		__set_bit(fd, fdt->full_fds_bits);
340 }
341 
342 static inline void __clear_open_fd(unsigned int fd, struct fdtable *fdt)
343 {
344 	__clear_bit(fd, fdt->open_fds);
345 	fd /= BITS_PER_LONG;
346 	if (test_bit(fd, fdt->full_fds_bits))
347 		__clear_bit(fd, fdt->full_fds_bits);
348 }
349 
350 static inline bool fd_is_open(unsigned int fd, const struct fdtable *fdt)
351 {
352 	return test_bit(fd, fdt->open_fds);
353 }
354 
355 /* Bits of [range->from, range->to] that fall into word @i of a bitmap. */
356 static unsigned long fd_range_word(struct fd_range *range, unsigned int i)
357 {
358 	unsigned int first = i * BITS_PER_LONG;
359 	unsigned int last = first + BITS_PER_LONG - 1;
360 
361 	if (range->to < first || range->from > last)
362 		return 0;
363 	return GENMASK(min(range->to, last) - first,
364 		       max(range->from, first) - first);
365 }
366 
367 /* Bits of word @i that dup_fd() leaves behind. */
368 static unsigned long dup_fd_dropped_word(struct fdtable *fdt, unsigned int i,
369 					 struct fd_range *range)
370 {
371 	unsigned long dropped;
372 
373 	if (!range)
374 		return 0;
375 	dropped = fd_range_word(range, i);
376 	if (range->flags & FD_RANGE_EXCEPT)
377 		dropped = ~dropped;
378 	if (range->flags & FD_RANGE_CLOEXEC_ONLY)
379 		dropped &= fdt->close_on_exec[i];
380 	return dropped;
381 }
382 
383 /*
384  * Note that a sane fdtable size always has to be a multiple of
385  * BITS_PER_LONG, since we have bitmaps that are sized by this.
386  *
387  * range is optional. When close_range() is asked to unshare dup_fd()
388  * will leave any files behind according to the range and its flags. The
389  * cloned table only has to reach the last open descriptor that is
390  * carried over.
391  */
392 static unsigned int sane_fdtable_size(struct fdtable *fdt, struct fd_range *range)
393 {
394 	unsigned int last = find_last_bit(fdt->open_fds, fdt->max_fds);
395 	unsigned int i;
396 
397 	if (last == fdt->max_fds)
398 		return NR_OPEN_DEFAULT;
399 	if (!range)
400 		return ALIGN(last + 1, BITS_PER_LONG);
401 
402 	if (range->flags & FD_RANGE_CLOEXEC_ONLY) {
403 		/* The close-on-exec bits decide what is dropped, walk the words. */
404 		i = last / BITS_PER_LONG + 1;
405 		while (i--) {
406 			unsigned long dropped = dup_fd_dropped_word(fdt, i, range);
407 
408 			if (fdt->open_fds[i] & ~dropped)
409 				return (i + 1) * BITS_PER_LONG;
410 		}
411 		return NR_OPEN_DEFAULT;
412 	}
413 
414 	if (range->flags & FD_RANGE_EXCEPT) {
415 		/* Only the range is carried over. */
416 		if (last > range->to) {
417 			last = find_last_bit(fdt->open_fds, range->to + 1);
418 			if (last > range->to)
419 				return NR_OPEN_DEFAULT;
420 		}
421 		if (last < range->from)
422 			return NR_OPEN_DEFAULT;
423 	} else if (last >= range->from && last <= range->to) {
424 		/* The last open descriptor goes, the kept ones sit below the range. */
425 		last = find_last_bit(fdt->open_fds, range->from);
426 		if (last == range->from)
427 			return NR_OPEN_DEFAULT;
428 	}
429 	return ALIGN(last + 1, BITS_PER_LONG);
430 }
431 
432 /*
433  * Allocate a new descriptor table and copy contents from the passed in
434  * instance.  Returns a pointer to cloned table on success, ERR_PTR()
435  * on failure.  For 'range' see sane_fdtable_size().
436  */
437 struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *range)
438 {
439 	struct files_struct *newf;
440 	struct file **old_fds, **new_fds;
441 	unsigned int open_files, fd;
442 	unsigned long dropped = 0;
443 	struct fdtable *old_fdt, *new_fdt;
444 
445 	newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
446 	if (!newf)
447 		return ERR_PTR(-ENOMEM);
448 
449 	atomic_set(&newf->count, 1);
450 
451 	spin_lock_init(&newf->file_lock);
452 	newf->resize_in_progress = false;
453 	init_waitqueue_head(&newf->resize_wait);
454 	newf->next_fd = 0;
455 	new_fdt = &newf->fdtab;
456 	new_fdt->max_fds = NR_OPEN_DEFAULT;
457 	new_fdt->close_on_exec = newf->close_on_exec_init;
458 	new_fdt->open_fds = newf->open_fds_init;
459 	new_fdt->full_fds_bits = newf->full_fds_bits_init;
460 	new_fdt->fd = &newf->fd_array[0];
461 
462 	spin_lock(&oldf->file_lock);
463 	old_fdt = files_fdtable(oldf);
464 	open_files = sane_fdtable_size(old_fdt, range);
465 
466 	/*
467 	 * Check whether we need to allocate a larger fd array and fd set.
468 	 */
469 	while (unlikely(open_files > new_fdt->max_fds)) {
470 		spin_unlock(&oldf->file_lock);
471 
472 		if (new_fdt != &newf->fdtab)
473 			__free_fdtable(new_fdt);
474 
475 		new_fdt = alloc_fdtable(open_files);
476 		if (IS_ERR(new_fdt)) {
477 			kmem_cache_free(files_cachep, newf);
478 			return ERR_CAST(new_fdt);
479 		}
480 
481 		/*
482 		 * Reacquire the oldf lock and a pointer to its fd table
483 		 * who knows it may have a new bigger fd table. We need
484 		 * the latest pointer.
485 		 */
486 		spin_lock(&oldf->file_lock);
487 		old_fdt = files_fdtable(oldf);
488 		open_files = sane_fdtable_size(old_fdt, range);
489 	}
490 
491 	copy_fd_bitmaps(new_fdt, old_fdt, open_files / BITS_PER_LONG);
492 
493 	old_fds = old_fdt->fd;
494 	new_fds = new_fdt->fd;
495 
496 	/*
497 	 * We may be racing against fd allocation from other threads using this
498 	 * files_struct, despite holding ->file_lock.
499 	 *
500 	 * alloc_fd() might have already claimed a slot, while fd_install()
501 	 * did not populate it yet. Note the latter operates locklessly, so
502 	 * the file can show up as we are walking the array below.
503 	 *
504 	 * At the same time we know no files will disappear as all other
505 	 * operations take the lock.
506 	 *
507 	 * Instead of trying to placate userspace racing with itself, we
508 	 * ref the file if we see it and mark the fd slot as unused otherwise.
509 	 * Descriptors dup_fd() is asked to leave behind get the same treatment.
510 	 */
511 	for (fd = 0; fd < open_files; fd++) {
512 		struct file *f = rcu_dereference_raw(*old_fds++);
513 
514 		if (!(fd % BITS_PER_LONG))
515 			dropped = dup_fd_dropped_word(old_fdt, fd / BITS_PER_LONG, range);
516 		if (f && !(dropped & BIT_MASK(fd))) {
517 			get_file(f);
518 		} else {
519 			f = NULL;
520 			__clear_open_fd(fd, new_fdt);
521 		}
522 		rcu_assign_pointer(*new_fds++, f);
523 	}
524 	spin_unlock(&oldf->file_lock);
525 
526 	/* clear the remainder */
527 	memset(new_fds, 0, (new_fdt->max_fds - open_files) * sizeof(struct file *));
528 
529 	rcu_assign_pointer(newf->fdt, new_fdt);
530 
531 	return newf;
532 }
533 
534 static struct fdtable *close_files(struct files_struct * files)
535 {
536 	/*
537 	 * It is safe to dereference the fd table without RCU or
538 	 * ->file_lock because this is the last reference to the
539 	 * files structure.
540 	 */
541 	struct fdtable *fdt = rcu_dereference_raw(files->fdt);
542 	unsigned int i, j = 0;
543 
544 	for (;;) {
545 		unsigned long set;
546 		i = j * BITS_PER_LONG;
547 		if (i >= fdt->max_fds)
548 			break;
549 		set = fdt->open_fds[j++];
550 		while (set) {
551 			if (set & 1) {
552 				struct file *file = fdt->fd[i];
553 				if (file) {
554 					filp_close(file, files);
555 					cond_resched();
556 				}
557 			}
558 			i++;
559 			set >>= 1;
560 		}
561 	}
562 
563 	return fdt;
564 }
565 
566 void put_files_struct(struct files_struct *files)
567 {
568 	if (atomic_dec_and_test(&files->count)) {
569 		struct fdtable *fdt = close_files(files);
570 
571 		/* free the arrays if they are not embedded */
572 		if (fdt != &files->fdtab)
573 			__free_fdtable(fdt);
574 		kmem_cache_free(files_cachep, files);
575 	}
576 }
577 
578 void exit_files(struct task_struct *tsk)
579 {
580 	struct files_struct * files = tsk->files;
581 
582 	if (files) {
583 		task_lock(tsk);
584 		tsk->files = NULL;
585 		task_unlock(tsk);
586 		put_files_struct(files);
587 	}
588 }
589 
590 struct files_struct init_files = {
591 	.count		= ATOMIC_INIT(1),
592 	.fdt		= &init_files.fdtab,
593 	.fdtab		= {
594 		.max_fds	= NR_OPEN_DEFAULT,
595 		.fd		= &init_files.fd_array[0],
596 		.close_on_exec	= init_files.close_on_exec_init,
597 		.open_fds	= init_files.open_fds_init,
598 		.full_fds_bits	= init_files.full_fds_bits_init,
599 	},
600 	.file_lock	= __SPIN_LOCK_UNLOCKED(init_files.file_lock),
601 	.resize_wait	= __WAIT_QUEUE_HEAD_INITIALIZER(init_files.resize_wait),
602 };
603 
604 static unsigned int find_next_fd(struct fdtable *fdt, unsigned int start)
605 {
606 	unsigned int maxfd = fdt->max_fds; /* always multiple of BITS_PER_LONG */
607 	unsigned int max_fds_words = maxfd / BITS_PER_LONG;
608 	unsigned int fds_word_idx = start / BITS_PER_LONG;
609 	unsigned int bit;
610 
611 	/*
612 	 * Try to avoid looking at the second level bitmap
613 	 */
614 	bit = find_next_zero_bit(&fdt->open_fds[fds_word_idx], BITS_PER_LONG,
615 				 start & (BITS_PER_LONG - 1));
616 	if (bit < BITS_PER_LONG)
617 		return bit + (fds_word_idx * BITS_PER_LONG);
618 
619 	bit = BITS_PER_LONG *
620 		find_next_zero_bit(fdt->full_fds_bits, max_fds_words, fds_word_idx + 1);
621 	if (bit >= maxfd)
622 		return maxfd;
623 	return find_next_zero_bit(fdt->open_fds, maxfd, bit);
624 }
625 
626 /*
627  * allocate a file descriptor, mark it busy.
628  */
629 static int alloc_fd(unsigned start, unsigned end, unsigned flags)
630 {
631 	struct files_struct *files = current->files;
632 	unsigned int fd;
633 	int error;
634 	struct fdtable *fdt;
635 
636 	spin_lock(&files->file_lock);
637 repeat:
638 	fdt = files_fdtable(files);
639 	fd = start;
640 	if (fd < files->next_fd)
641 		fd = files->next_fd;
642 
643 	if (likely(fd < fdt->max_fds))
644 		fd = find_next_fd(fdt, fd);
645 
646 	/*
647 	 * N.B. For clone tasks sharing a files structure, this test
648 	 * will limit the total number of files that can be opened.
649 	 */
650 	error = -EMFILE;
651 	if (unlikely(fd >= end))
652 		goto out;
653 
654 	if (unlikely(fd >= fdt->max_fds)) {
655 		error = expand_files(files, fd);
656 		if (error < 0)
657 			goto out;
658 
659 		goto repeat;
660 	}
661 
662 	if (start <= files->next_fd)
663 		files->next_fd = fd + 1;
664 
665 	__set_open_fd(fd, fdt, flags & O_CLOEXEC);
666 	error = fd;
667 	VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
668 
669 out:
670 	spin_unlock(&files->file_lock);
671 	return error;
672 }
673 
674 int __get_unused_fd_flags(unsigned flags, unsigned long nofile)
675 {
676 	return alloc_fd(0, nofile, flags);
677 }
678 
679 int get_unused_fd_flags(unsigned flags)
680 {
681 	return __get_unused_fd_flags(flags, rlimit(RLIMIT_NOFILE));
682 }
683 EXPORT_SYMBOL(get_unused_fd_flags);
684 
685 static void __put_unused_fd(struct files_struct *files, unsigned int fd)
686 {
687 	struct fdtable *fdt = files_fdtable(files);
688 	__clear_open_fd(fd, fdt);
689 	if (fd < files->next_fd)
690 		files->next_fd = fd;
691 }
692 
693 void put_unused_fd(unsigned int fd)
694 {
695 	struct files_struct *files = current->files;
696 	spin_lock(&files->file_lock);
697 	__put_unused_fd(files, fd);
698 	spin_unlock(&files->file_lock);
699 }
700 
701 EXPORT_SYMBOL(put_unused_fd);
702 
703 /*
704  * Install a file pointer in the fd array while it is being resized.
705  *
706  * We need to make sure our update to the array does not get lost as the resizing
707  * thread can be copying the content as we modify it.
708  *
709  * We have two ways to do it:
710  * - go off CPU waiting for resize_in_progress to clear
711  * - take the spin lock
712  *
713  * The latter is trivial to implement and saves us from having to might_sleep()
714  * for debugging purposes.
715  *
716  * This is moved out of line from fd_install() to convince gcc to optimize that
717  * routine better.
718  */
719 static void noinline fd_install_slowpath(unsigned int fd, struct file *file)
720 {
721 	struct files_struct *files = current->files;
722 	struct fdtable *fdt;
723 
724 	spin_lock(&files->file_lock);
725 	fdt = files_fdtable(files);
726 	VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
727 	rcu_assign_pointer(fdt->fd[fd], file);
728 	spin_unlock(&files->file_lock);
729 }
730 
731 /**
732  * fd_install - install a file pointer in the fd array
733  * @fd: file descriptor to install the file in
734  * @file: the file to install
735  *
736  * This consumes the "file" refcount, so callers should treat it
737  * as if they had called fput(file).
738  */
739 void fd_install(unsigned int fd, struct file *file)
740 {
741 	struct files_struct *files = current->files;
742 	struct fdtable *fdt;
743 
744 	if (WARN_ON_ONCE(unlikely(file->f_mode & FMODE_BACKING)))
745 		return;
746 
747 	rcu_read_lock_sched();
748 	if (unlikely(files->resize_in_progress)) {
749 		rcu_read_unlock_sched();
750 		fd_install_slowpath(fd, file);
751 		return;
752 	}
753 	/* coupled with smp_wmb() in expand_fdtable() */
754 	smp_rmb();
755 	fdt = rcu_dereference_sched(files->fdt);
756 	VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
757 	rcu_assign_pointer(fdt->fd[fd], file);
758 	rcu_read_unlock_sched();
759 }
760 
761 EXPORT_SYMBOL(fd_install);
762 
763 /**
764  * file_close_fd_locked - return file associated with fd
765  * @files: file struct to retrieve file from
766  * @fd: file descriptor to retrieve file for
767  *
768  * Doesn't take a separate reference count.
769  *
770  * Context: files_lock must be held.
771  *
772  * Returns: The file associated with @fd (NULL if @fd is not open)
773  */
774 struct file *file_close_fd_locked(struct files_struct *files, unsigned fd)
775 {
776 	struct fdtable *fdt = files_fdtable(files);
777 	struct file *file;
778 
779 	lockdep_assert_held(&files->file_lock);
780 
781 	if (fd >= fdt->max_fds)
782 		return NULL;
783 
784 	fd = array_index_nospec(fd, fdt->max_fds);
785 	file = rcu_dereference_raw(fdt->fd[fd]);
786 	if (file) {
787 		rcu_assign_pointer(fdt->fd[fd], NULL);
788 		__put_unused_fd(files, fd);
789 	}
790 	return file;
791 }
792 
793 int close_fd(unsigned fd)
794 {
795 	struct files_struct *files = current->files;
796 	struct file *file;
797 
798 	spin_lock(&files->file_lock);
799 	file = file_close_fd_locked(files, fd);
800 	spin_unlock(&files->file_lock);
801 	if (!file)
802 		return -EBADF;
803 
804 	return filp_close(file, files);
805 }
806 EXPORT_SYMBOL(close_fd);
807 
808 /**
809  * last_fd - return last valid index into fd table
810  * @fdt: File descriptor table.
811  *
812  * Context: Either rcu read lock or files_lock must be held.
813  *
814  * Returns: Last valid index into fdtable.
815  */
816 static inline unsigned last_fd(struct fdtable *fdt)
817 {
818 	return fdt->max_fds - 1;
819 }
820 
821 static inline void __range_cloexec(struct files_struct *cur_fds,
822 				   struct fd_range *range)
823 {
824 	struct fdtable *fdt;
825 	unsigned int last;
826 
827 	spin_lock(&cur_fds->file_lock);
828 	fdt = files_fdtable(cur_fds);
829 	/* make sure we're using the correct maximum value */
830 	last = last_fd(fdt);
831 	if (!(range->flags & FD_RANGE_EXCEPT)) {
832 		if (range->from <= last)
833 			bitmap_set(fdt->close_on_exec, range->from,
834 				   min(range->to, last) - range->from + 1);
835 	} else {
836 		if (range->from > 0)
837 			bitmap_set(fdt->close_on_exec, 0,
838 				   min(range->from - 1, last) + 1);
839 		if (range->to < last)
840 			bitmap_set(fdt->close_on_exec, range->to + 1,
841 				   last - range->to);
842 	}
843 	spin_unlock(&cur_fds->file_lock);
844 }
845 
846 /* Next open descriptor in [fd, max_fd], or the next close-on-exec one. */
847 static inline unsigned int next_open_fd(struct fdtable *fdt, unsigned int fd,
848 					unsigned int max_fd,
849 					struct fd_range *range)
850 {
851 	if (range->flags & FD_RANGE_CLOEXEC_ONLY)
852 		return find_next_and_bit(fdt->open_fds, fdt->close_on_exec,
853 					 max_fd + 1, fd);
854 	return find_next_bit(fdt->open_fds, max_fd + 1, fd);
855 }
856 
857 /* Next open descriptor in [fd, max_fd] that @range selects. */
858 static inline unsigned int next_fd_to_close(struct fdtable *fdt,
859 					    unsigned int fd, unsigned int max_fd,
860 					    struct fd_range *range)
861 {
862 	fd = next_open_fd(fdt, fd, max_fd, range);
863 	/* Hop over the window the range keeps. */
864 	if ((range->flags & FD_RANGE_EXCEPT) &&
865 	    fd >= range->from && fd <= range->to) {
866 		if (range->to >= max_fd)
867 			return max_fd + 1;
868 		fd = next_open_fd(fdt, range->to + 1, max_fd, range);
869 	}
870 	return fd;
871 }
872 
873 static inline void __range_close(struct files_struct *files,
874 				 struct fd_range *range)
875 {
876 	struct file *file;
877 	struct fdtable *fdt;
878 	unsigned int fd, max_fd;
879 
880 	spin_lock(&files->file_lock);
881 	fdt = files_fdtable(files);
882 	if (range->flags & FD_RANGE_EXCEPT) {
883 		/* Outside of the range means the whole table. */
884 		fd = 0;
885 		max_fd = last_fd(fdt);
886 	} else {
887 		fd = range->from;
888 		max_fd = min(range->to, last_fd(fdt));
889 	}
890 
891 	for (fd = next_fd_to_close(fdt, fd, max_fd, range);
892 	     fd <= max_fd;
893 	     fd = next_fd_to_close(fdt, fd + 1, max_fd, range)) {
894 		file = file_close_fd_locked(files, fd);
895 		if (file) {
896 			spin_unlock(&files->file_lock);
897 			filp_close(file, files);
898 			cond_resched();
899 			spin_lock(&files->file_lock);
900 			fdt = files_fdtable(files);
901 		} else if (need_resched()) {
902 			spin_unlock(&files->file_lock);
903 			cond_resched();
904 			spin_lock(&files->file_lock);
905 			fdt = files_fdtable(files);
906 		}
907 	}
908 	spin_unlock(&files->file_lock);
909 }
910 
911 /**
912  * sys_close_range() - Close all file descriptors in a given range.
913  *
914  * @fd:     starting file descriptor to close
915  * @max_fd: last file descriptor to close
916  * @flags:  CLOSE_RANGE flags.
917  *
918  * This closes a range of file descriptors. All file descriptors
919  * from @fd up to and including @max_fd are closed.
920  * Currently, errors to close a given file descriptor are ignored.
921  *
922  * With CLOSE_RANGE_EXCEPT the range names what to leave alone instead:
923  * every open file descriptor outside of [@fd, @max_fd] is closed, or
924  * marked close-on-exec with CLOSE_RANGE_CLOEXEC.
925  *
926  * With CLOSE_RANGE_CLOEXEC_ONLY only file descriptors that have
927  * close-on-exec set are closed. Together with CLOSE_RANGE_EXCEPT the
928  * range names the close-on-exec file descriptors to keep. To keep none
929  * of them, name a range that cannot hold an open file descriptor, e.g.
930  * close_range(~0U, ~0U, ...).
931  */
932 SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
933 		unsigned int, flags)
934 {
935 	struct task_struct *me = current;
936 	struct files_struct *cur_fds = me->files, *fds = NULL;
937 	struct fd_range range = {fd, max_fd};
938 
939 	if (flags & ~(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC |
940 		      CLOSE_RANGE_EXCEPT | CLOSE_RANGE_CLOEXEC_ONLY))
941 		return -EINVAL;
942 
943 	/* One marks close-on-exec, the other closes what is marked. */
944 	if (hweight32(flags & (CLOSE_RANGE_CLOEXEC |
945 			       CLOSE_RANGE_CLOEXEC_ONLY)) > 1)
946 		return -EINVAL;
947 
948 	if (fd > max_fd)
949 		return -EINVAL;
950 
951 	if (flags & CLOSE_RANGE_EXCEPT)
952 		range.flags |= FD_RANGE_EXCEPT;
953 	if (flags & CLOSE_RANGE_CLOEXEC_ONLY)
954 		range.flags |= FD_RANGE_CLOEXEC_ONLY;
955 
956 	if ((flags & CLOSE_RANGE_UNSHARE) && atomic_read(&cur_fds->count) > 1) {
957 		struct fd_range *drop = &range;
958 
959 		/*
960 		 * If the caller requested all fds to be made cloexec we always
961 		 * copy all of the file descriptors since they still want to
962 		 * use them.
963 		 */
964 		if (flags & CLOSE_RANGE_CLOEXEC)
965 			drop = NULL;
966 
967 		fds = dup_fd(cur_fds, drop);
968 		if (IS_ERR(fds))
969 			return PTR_ERR(fds);
970 		/*
971 		 * We used to share our file descriptor table, and have now
972 		 * created a private one, make sure we're using it below.
973 		 */
974 		swap(cur_fds, fds);
975 	}
976 
977 	if (flags & CLOSE_RANGE_CLOEXEC) {
978 		__range_cloexec(cur_fds, &range);
979 	} else if (!fds) {
980 		/* If we unshared, dup_fd() already left behind what we'd close. */
981 		__range_close(cur_fds, &range);
982 	}
983 
984 	if (fds) {
985 		/*
986 		 * We're done closing the files we were supposed to. Time to install
987 		 * the new file descriptor table and drop the old one.
988 		 */
989 		task_lock(me);
990 		me->files = cur_fds;
991 		task_unlock(me);
992 		put_files_struct(fds);
993 	}
994 
995 	return 0;
996 }
997 
998 /**
999  * file_close_fd - return file associated with fd
1000  * @fd: file descriptor to retrieve file for
1001  *
1002  * Doesn't take a separate reference count.
1003  *
1004  * Returns: The file associated with @fd (NULL if @fd is not open)
1005  */
1006 struct file *file_close_fd(unsigned int fd)
1007 {
1008 	struct files_struct *files = current->files;
1009 	struct file *file;
1010 
1011 	spin_lock(&files->file_lock);
1012 	file = file_close_fd_locked(files, fd);
1013 	spin_unlock(&files->file_lock);
1014 
1015 	return file;
1016 }
1017 
1018 void do_close_on_exec(struct files_struct *files)
1019 {
1020 	unsigned i;
1021 	struct fdtable *fdt;
1022 
1023 	/* exec unshares first */
1024 	spin_lock(&files->file_lock);
1025 	for (i = 0; ; i++) {
1026 		unsigned long set;
1027 		unsigned fd = i * BITS_PER_LONG;
1028 		fdt = files_fdtable(files);
1029 		if (fd >= fdt->max_fds)
1030 			break;
1031 		set = fdt->close_on_exec[i];
1032 		if (!set)
1033 			continue;
1034 		fdt->close_on_exec[i] = 0;
1035 		for ( ; set ; fd++, set >>= 1) {
1036 			struct file *file;
1037 			if (!(set & 1))
1038 				continue;
1039 			file = fdt->fd[fd];
1040 			if (!file)
1041 				continue;
1042 			rcu_assign_pointer(fdt->fd[fd], NULL);
1043 			__put_unused_fd(files, fd);
1044 			spin_unlock(&files->file_lock);
1045 			filp_close(file, files);
1046 			cond_resched();
1047 			spin_lock(&files->file_lock);
1048 		}
1049 
1050 	}
1051 	spin_unlock(&files->file_lock);
1052 }
1053 
1054 static struct file *__get_file_rcu(struct file __rcu **f)
1055 {
1056 	struct file __rcu *file;
1057 	struct file __rcu *file_reloaded;
1058 	struct file __rcu *file_reloaded_cmp;
1059 
1060 	file = rcu_dereference_raw(*f);
1061 	if (!file)
1062 		return NULL;
1063 
1064 	if (unlikely(!file_ref_get(&file->f_ref)))
1065 		return ERR_PTR(-EAGAIN);
1066 
1067 	file_reloaded = rcu_dereference_raw(*f);
1068 
1069 	/*
1070 	 * Ensure that all accesses have a dependency on the load from
1071 	 * rcu_dereference_raw() above so we get correct ordering
1072 	 * between reuse/allocation and the pointer check below.
1073 	 */
1074 	file_reloaded_cmp = file_reloaded;
1075 	OPTIMIZER_HIDE_VAR(file_reloaded_cmp);
1076 
1077 	/*
1078 	 * file_ref_get() above provided a full memory barrier when we
1079 	 * acquired a reference.
1080 	 *
1081 	 * This is paired with the write barrier from assigning to the
1082 	 * __rcu protected file pointer so that if that pointer still
1083 	 * matches the current file, we know we have successfully
1084 	 * acquired a reference to the right file.
1085 	 *
1086 	 * If the pointers don't match the file has been reallocated by
1087 	 * SLAB_TYPESAFE_BY_RCU.
1088 	 */
1089 	if (file == file_reloaded_cmp)
1090 		return file_reloaded;
1091 
1092 	fput(file);
1093 	return ERR_PTR(-EAGAIN);
1094 }
1095 
1096 /**
1097  * get_file_rcu - try go get a reference to a file under rcu
1098  * @f: the file to get a reference on
1099  *
1100  * This function tries to get a reference on @f carefully verifying that
1101  * @f hasn't been reused.
1102  *
1103  * This function should rarely have to be used and only by users who
1104  * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
1105  *
1106  * Return: Returns @f with the reference count increased or NULL.
1107  */
1108 struct file *get_file_rcu(struct file __rcu **f)
1109 {
1110 	for (;;) {
1111 		struct file __rcu *file;
1112 
1113 		file = __get_file_rcu(f);
1114 		if (!IS_ERR(file))
1115 			return file;
1116 	}
1117 }
1118 EXPORT_SYMBOL_GPL(get_file_rcu);
1119 
1120 /**
1121  * get_file_active - try go get a reference to a file
1122  * @f: the file to get a reference on
1123  *
1124  * In contast to get_file_rcu() the pointer itself isn't part of the
1125  * reference counting.
1126  *
1127  * This function should rarely have to be used and only by users who
1128  * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
1129  *
1130  * Return: Returns @f with the reference count increased or NULL.
1131  */
1132 struct file *get_file_active(struct file **f)
1133 {
1134 	struct file __rcu *file;
1135 
1136 	rcu_read_lock();
1137 	file = __get_file_rcu(f);
1138 	rcu_read_unlock();
1139 	if (IS_ERR(file))
1140 		file = NULL;
1141 	return file;
1142 }
1143 EXPORT_SYMBOL_GPL(get_file_active);
1144 
1145 static inline struct file *__fget_files_rcu(struct files_struct *files,
1146        unsigned int fd, fmode_t mask)
1147 {
1148 	for (;;) {
1149 		struct file *file;
1150 		struct fdtable *fdt = rcu_dereference_raw(files->fdt);
1151 		struct file __rcu **fdentry;
1152 		unsigned long nospec_mask;
1153 
1154 		/* Mask is a 0 for invalid fd's, ~0 for valid ones */
1155 		nospec_mask = array_index_mask_nospec(fd, fdt->max_fds);
1156 
1157 		/*
1158 		 * fdentry points to the 'fd' offset, or fdt->fd[0].
1159 		 * Loading from fdt->fd[0] is always safe, because the
1160 		 * array always exists.
1161 		 */
1162 		fdentry = fdt->fd + (fd & nospec_mask);
1163 
1164 		/* Do the load, then mask any invalid result */
1165 		file = rcu_dereference_raw(*fdentry);
1166 		file = (void *)(nospec_mask & (unsigned long)file);
1167 		if (unlikely(!file))
1168 			return NULL;
1169 
1170 		/*
1171 		 * Ok, we have a file pointer that was valid at
1172 		 * some point, but it might have become stale since.
1173 		 *
1174 		 * We need to confirm it by incrementing the refcount
1175 		 * and then check the lookup again.
1176 		 *
1177 		 * file_ref_get() gives us a full memory barrier. We
1178 		 * only really need an 'acquire' one to protect the
1179 		 * loads below, but we don't have that.
1180 		 */
1181 		if (unlikely(!file_ref_get(&file->f_ref)))
1182 			continue;
1183 
1184 		/*
1185 		 * Such a race can take two forms:
1186 		 *
1187 		 *  (a) the file ref already went down to zero and the
1188 		 *      file hasn't been reused yet or the file count
1189 		 *      isn't zero but the file has already been reused.
1190 		 *
1191 		 *  (b) the file table entry has changed under us.
1192 		 *       Note that we don't need to re-check the 'fdt->fd'
1193 		 *       pointer having changed, because it always goes
1194 		 *       hand-in-hand with 'fdt'.
1195 		 *
1196 		 * If so, we need to put our ref and try again.
1197 		 */
1198 		if (unlikely(file != rcu_dereference_raw(*fdentry)) ||
1199 		    unlikely(rcu_dereference_raw(files->fdt) != fdt)) {
1200 			fput(file);
1201 			continue;
1202 		}
1203 
1204 		/*
1205 		 * This isn't the file we're looking for or we're not
1206 		 * allowed to get a reference to it.
1207 		 */
1208 		if (unlikely(file->f_mode & mask)) {
1209 			fput(file);
1210 			return NULL;
1211 		}
1212 
1213 		/*
1214 		 * Ok, we have a ref to the file, and checked that it
1215 		 * still exists.
1216 		 */
1217 		return file;
1218 	}
1219 }
1220 
1221 static struct file *__fget_files(struct files_struct *files, unsigned int fd,
1222 				 fmode_t mask)
1223 {
1224 	struct file *file;
1225 
1226 	rcu_read_lock();
1227 	file = __fget_files_rcu(files, fd, mask);
1228 	rcu_read_unlock();
1229 
1230 	return file;
1231 }
1232 
1233 static inline struct file *__fget(unsigned int fd, fmode_t mask)
1234 {
1235 	return __fget_files(current->files, fd, mask);
1236 }
1237 
1238 struct file *fget(unsigned int fd)
1239 {
1240 	return __fget(fd, FMODE_PATH);
1241 }
1242 EXPORT_SYMBOL(fget);
1243 
1244 struct file *fget_raw(unsigned int fd)
1245 {
1246 	return __fget(fd, 0);
1247 }
1248 EXPORT_SYMBOL(fget_raw);
1249 
1250 struct file *fget_task(struct task_struct *task, unsigned int fd)
1251 {
1252 	struct file *file = NULL;
1253 
1254 	task_lock(task);
1255 	if (task->files)
1256 		file = __fget_files(task->files, fd, 0);
1257 	task_unlock(task);
1258 
1259 	return file;
1260 }
1261 
1262 struct file *fget_task_next(struct task_struct *task, unsigned int *ret_fd)
1263 {
1264 	struct files_struct *files;
1265 	unsigned int fd = *ret_fd;
1266 	struct file *file = NULL;
1267 
1268 	task_lock(task);
1269 	files = task->files;
1270 	if (files) {
1271 		rcu_read_lock();
1272 		for (; fd < files_fdtable(files)->max_fds; fd++) {
1273 			file = __fget_files_rcu(files, fd, 0);
1274 			if (file)
1275 				break;
1276 		}
1277 		rcu_read_unlock();
1278 	}
1279 	task_unlock(task);
1280 	*ret_fd = fd;
1281 	return file;
1282 }
1283 EXPORT_SYMBOL(fget_task_next);
1284 
1285 /*
1286  * Lightweight file lookup - no refcnt increment if fd table isn't shared.
1287  *
1288  * You can use this instead of fget if you satisfy all of the following
1289  * conditions:
1290  * 1) You must call fput_light before exiting the syscall and returning control
1291  *    to userspace (i.e. you cannot remember the returned struct file * after
1292  *    returning to userspace).
1293  * 2) You must not call filp_close on the returned struct file * in between
1294  *    calls to fget_light and fput_light.
1295  * 3) You must not clone the current task in between the calls to fget_light
1296  *    and fput_light.
1297  *
1298  * The fput_needed flag returned by fget_light should be passed to the
1299  * corresponding fput_light.
1300  *
1301  * (As an exception to rule 2, you can call filp_close between fget_light and
1302  * fput_light provided that you capture a real refcount with get_file before
1303  * the call to filp_close, and ensure that this real refcount is fput *after*
1304  * the fput_light call.)
1305  *
1306  * See also the documentation in rust/kernel/file.rs.
1307  */
1308 static inline struct fd __fget_light(unsigned int fd, fmode_t mask)
1309 {
1310 	struct files_struct *files = current->files;
1311 	struct file *file;
1312 
1313 	/*
1314 	 * If another thread is concurrently calling close_fd() followed
1315 	 * by put_files_struct(), we must not observe the old table
1316 	 * entry combined with the new refcount - otherwise we could
1317 	 * return a file that is concurrently being freed.
1318 	 *
1319 	 * atomic_read_acquire() pairs with atomic_dec_and_test() in
1320 	 * put_files_struct().
1321 	 */
1322 	if (likely(atomic_read_acquire(&files->count) == 1)) {
1323 		file = files_lookup_fd_raw(files, fd);
1324 		if (!file || unlikely(file->f_mode & mask))
1325 			return EMPTY_FD;
1326 		return BORROWED_FD(file);
1327 	} else {
1328 		file = __fget_files(files, fd, mask);
1329 		if (!file)
1330 			return EMPTY_FD;
1331 		return CLONED_FD(file);
1332 	}
1333 }
1334 struct fd fdget(unsigned int fd)
1335 {
1336 	return __fget_light(fd, FMODE_PATH);
1337 }
1338 EXPORT_SYMBOL(fdget);
1339 
1340 struct fd fdget_raw(unsigned int fd)
1341 {
1342 	return __fget_light(fd, 0);
1343 }
1344 
1345 /*
1346  * Try to avoid f_pos locking. We only need it if the
1347  * file is marked for FMODE_ATOMIC_POS, and it can be
1348  * accessed multiple ways.
1349  *
1350  * Always do it for directories, because pidfd_getfd()
1351  * can make a file accessible even if it otherwise would
1352  * not be, and for directories this is a correctness
1353  * issue, not a "POSIX requirement".
1354  */
1355 static inline bool file_needs_f_pos_lock(struct file *file)
1356 {
1357 	if (!(file->f_mode & FMODE_ATOMIC_POS))
1358 		return false;
1359 	if (__file_ref_read_raw(&file->f_ref) != FILE_REF_ONEREF)
1360 		return true;
1361 	if (file->f_op->iterate_shared)
1362 		return true;
1363 	return false;
1364 }
1365 
1366 bool file_seek_cur_needs_f_lock(struct file *file)
1367 {
1368 	if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared)
1369 		return false;
1370 
1371 	/*
1372 	 * Note that we are not guaranteed to be called after fdget_pos() on
1373 	 * this file obj, in which case the caller is expected to provide the
1374 	 * appropriate locking.
1375 	 */
1376 
1377 	return true;
1378 }
1379 
1380 struct fd fdget_pos(unsigned int fd)
1381 {
1382 	struct fd f = fdget(fd);
1383 	struct file *file = fd_file(f);
1384 
1385 	if (likely(file) && file_needs_f_pos_lock(file)) {
1386 		f.word |= FDPUT_POS_UNLOCK;
1387 		mutex_lock(&file->f_pos_lock);
1388 	}
1389 	return f;
1390 }
1391 
1392 void __f_unlock_pos(struct file *f)
1393 {
1394 	mutex_unlock(&f->f_pos_lock);
1395 }
1396 
1397 /*
1398  * We only lock f_pos if we have threads or if the file might be
1399  * shared with another process. In both cases we'll have an elevated
1400  * file count (done either by fdget() or by fork()).
1401  */
1402 
1403 void set_close_on_exec(unsigned int fd, int flag)
1404 {
1405 	struct files_struct *files = current->files;
1406 	spin_lock(&files->file_lock);
1407 	__set_close_on_exec(fd, files_fdtable(files), flag);
1408 	spin_unlock(&files->file_lock);
1409 }
1410 
1411 bool get_close_on_exec(unsigned int fd)
1412 {
1413 	bool res;
1414 	rcu_read_lock();
1415 	res = close_on_exec(fd, current->files);
1416 	rcu_read_unlock();
1417 	return res;
1418 }
1419 
1420 static int do_dup2(struct files_struct *files,
1421 	struct file *file, unsigned fd, unsigned flags)
1422 __releases(&files->file_lock)
1423 {
1424 	struct file *tofree;
1425 	struct fdtable *fdt;
1426 
1427 	/*
1428 	 * dup2() is expected to close the file installed in the target fd slot
1429 	 * (if any). However, userspace hand-picking a fd may be racing against
1430 	 * its own threads which happened to allocate it in open() et al but did
1431 	 * not populate it yet.
1432 	 *
1433 	 * Broadly speaking we may be racing against the following:
1434 	 * fd = get_unused_fd_flags();     // fd slot reserved, ->fd[fd] == NULL
1435 	 * file = hard_work_goes_here();
1436 	 * fd_install(fd, file);           // only now ->fd[fd] == file
1437 	 *
1438 	 * It is an invariant that a successfully allocated fd has a NULL entry
1439 	 * in the array until the matching fd_install().
1440 	 *
1441 	 * If we fit the window, we have the fd to populate, yet no target file
1442 	 * to close. Trying to ignore it and install our new file would violate
1443 	 * the invariant and make fd_install() overwrite our file.
1444 	 *
1445 	 * Things can be done(tm) to handle this. However, the issue does not
1446 	 * concern legitimate programs and we only need to make sure the kernel
1447 	 * does not trip over it.
1448 	 *
1449 	 * The simplest way out is to return an error if we find ourselves here.
1450 	 *
1451 	 * POSIX is silent on the issue, we return -EBUSY.
1452 	 */
1453 	fdt = files_fdtable(files);
1454 	fd = array_index_nospec(fd, fdt->max_fds);
1455 	tofree = rcu_dereference_raw(fdt->fd[fd]);
1456 	if (!tofree && fd_is_open(fd, fdt))
1457 		goto Ebusy;
1458 	get_file(file);
1459 	rcu_assign_pointer(fdt->fd[fd], file);
1460 	__set_open_fd(fd, fdt, flags & O_CLOEXEC);
1461 	spin_unlock(&files->file_lock);
1462 
1463 	if (tofree)
1464 		filp_close(tofree, files);
1465 
1466 	return fd;
1467 
1468 Ebusy:
1469 	spin_unlock(&files->file_lock);
1470 	return -EBUSY;
1471 }
1472 
1473 int replace_fd(unsigned fd, struct file *file, unsigned flags)
1474 {
1475 	int err;
1476 	struct files_struct *files = current->files;
1477 
1478 	if (!file)
1479 		return close_fd(fd);
1480 
1481 	if (fd >= rlimit(RLIMIT_NOFILE))
1482 		return -EBADF;
1483 
1484 	spin_lock(&files->file_lock);
1485 	err = expand_files(files, fd);
1486 	if (unlikely(err < 0))
1487 		goto out_unlock;
1488 	err = do_dup2(files, file, fd, flags);
1489 	if (err < 0)
1490 		return err;
1491 	return 0;
1492 
1493 out_unlock:
1494 	spin_unlock(&files->file_lock);
1495 	return err;
1496 }
1497 
1498 /**
1499  * receive_fd() - Install received file into file descriptor table
1500  * @file: struct file that was received from another process
1501  * @ufd: __user pointer to write new fd number to
1502  * @o_flags: the O_* flags to apply to the new fd entry
1503  *
1504  * Installs a received file into the file descriptor table, with appropriate
1505  * checks and count updates. Optionally writes the fd number to userspace, if
1506  * @ufd is non-NULL.
1507  *
1508  * This helper handles its own reference counting of the incoming
1509  * struct file.
1510  *
1511  * Returns newly install fd or -ve on error.
1512  */
1513 int receive_fd(struct file *file, int __user *ufd, unsigned int o_flags)
1514 {
1515 	int error;
1516 
1517 	error = security_file_receive(file);
1518 	if (error)
1519 		return error;
1520 
1521 	FD_PREPARE(fdf, o_flags, file);
1522 	if (fdf->fd < 0)
1523 		return fdf->fd;
1524 	get_file(file);
1525 
1526 	if (ufd) {
1527 		error = put_user(fdf->fd, ufd);
1528 		if (error)
1529 			return error;
1530 	}
1531 
1532 	__receive_sock(fdf->file);
1533 	return fd_publish(fdf);
1534 }
1535 EXPORT_SYMBOL_GPL(receive_fd);
1536 
1537 int receive_fd_replace(int new_fd, struct file *file, unsigned int o_flags)
1538 {
1539 	int error;
1540 
1541 	error = security_file_receive(file);
1542 	if (error)
1543 		return error;
1544 	error = replace_fd(new_fd, file, o_flags);
1545 	if (error)
1546 		return error;
1547 	__receive_sock(file);
1548 	return new_fd;
1549 }
1550 
1551 static int ksys_dup3(unsigned int oldfd, unsigned int newfd, int flags)
1552 {
1553 	int err = -EBADF;
1554 	struct file *file;
1555 	struct files_struct *files = current->files;
1556 
1557 	if ((flags & ~O_CLOEXEC) != 0)
1558 		return -EINVAL;
1559 
1560 	if (unlikely(oldfd == newfd))
1561 		return -EINVAL;
1562 
1563 	if (newfd >= rlimit(RLIMIT_NOFILE))
1564 		return -EBADF;
1565 
1566 	spin_lock(&files->file_lock);
1567 	err = expand_files(files, newfd);
1568 	file = files_lookup_fd_locked(files, oldfd);
1569 	if (unlikely(!file))
1570 		goto Ebadf;
1571 	if (unlikely(err < 0)) {
1572 		if (err == -EMFILE)
1573 			goto Ebadf;
1574 		goto out_unlock;
1575 	}
1576 	return do_dup2(files, file, newfd, flags);
1577 
1578 Ebadf:
1579 	err = -EBADF;
1580 out_unlock:
1581 	spin_unlock(&files->file_lock);
1582 	return err;
1583 }
1584 
1585 SYSCALL_DEFINE3(dup3, unsigned int, oldfd, unsigned int, newfd, int, flags)
1586 {
1587 	return ksys_dup3(oldfd, newfd, flags);
1588 }
1589 
1590 SYSCALL_DEFINE2(dup2, unsigned int, oldfd, unsigned int, newfd)
1591 {
1592 	if (unlikely(newfd == oldfd)) { /* corner case */
1593 		struct files_struct *files = current->files;
1594 		struct file *f;
1595 		int retval = oldfd;
1596 
1597 		rcu_read_lock();
1598 		f = __fget_files_rcu(files, oldfd, 0);
1599 		if (!f)
1600 			retval = -EBADF;
1601 		rcu_read_unlock();
1602 		if (f)
1603 			fput(f);
1604 		return retval;
1605 	}
1606 	return ksys_dup3(oldfd, newfd, 0);
1607 }
1608 
1609 SYSCALL_DEFINE1(dup, unsigned int, fildes)
1610 {
1611 	int ret = -EBADF;
1612 	struct file *file = fget_raw(fildes);
1613 
1614 	if (file) {
1615 		ret = get_unused_fd_flags(0);
1616 		if (ret >= 0)
1617 			fd_install(ret, file);
1618 		else
1619 			fput(file);
1620 	}
1621 	return ret;
1622 }
1623 
1624 int f_dupfd(unsigned int from, struct file *file, unsigned flags)
1625 {
1626 	unsigned long nofile = rlimit(RLIMIT_NOFILE);
1627 	int err;
1628 	if (from >= nofile)
1629 		return -EINVAL;
1630 	err = alloc_fd(from, nofile, flags);
1631 	if (err >= 0) {
1632 		get_file(file);
1633 		fd_install(err, file);
1634 	}
1635 	return err;
1636 }
1637 
1638 int iterate_fd(struct files_struct *files, unsigned n,
1639 		int (*f)(const void *, struct file *, unsigned),
1640 		const void *p)
1641 {
1642 	struct fdtable *fdt;
1643 	int res = 0;
1644 	if (!files)
1645 		return 0;
1646 	spin_lock(&files->file_lock);
1647 	for (fdt = files_fdtable(files); n < fdt->max_fds; n++) {
1648 		struct file *file;
1649 		file = rcu_dereference_check_fdtable(files, fdt->fd[n]);
1650 		if (!file)
1651 			continue;
1652 		res = f(p, file, n);
1653 		if (res)
1654 			break;
1655 	}
1656 	spin_unlock(&files->file_lock);
1657 	return res;
1658 }
1659 EXPORT_SYMBOL(iterate_fd);
1660 
1661 #ifdef CONFIG_FDTABLE_KUNIT_TEST
1662 #include "tests/fdtable_kunit.c"
1663 #endif
1664