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
__file_ref_put_badval(file_ref_t * ref,unsigned long cnt)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 */
__file_ref_put(file_ref_t * ref,unsigned long cnt)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
__free_fdtable(struct fdtable * fdt)103 static void __free_fdtable(struct fdtable *fdt)
104 {
105 kvfree(fdt->fd);
106 kvfree(fdt->open_fds);
107 kfree(fdt);
108 }
109
free_fdtable_rcu(struct rcu_head * rcu)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 */
copy_fd_bitmaps(struct fdtable * nfdt,struct fdtable * ofdt,unsigned int copy_words)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 */
copy_fdtable(struct fdtable * nfdt,struct fdtable * ofdt)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 */
alloc_fdtable(unsigned int slots_wanted)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_cachep 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 */
expand_fdtable(struct files_struct * files,unsigned int nr)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 */
expand_files(struct files_struct * files,unsigned int nr)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
__set_close_on_exec(unsigned int fd,struct fdtable * fdt,bool set)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
__set_open_fd(unsigned int fd,struct fdtable * fdt,bool set)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
__clear_open_fd(unsigned int fd,struct fdtable * fdt)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
fd_is_open(unsigned int fd,const struct fdtable * fdt)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 /*
356 * Note that a sane fdtable size always has to be a multiple of
357 * BITS_PER_LONG, since we have bitmaps that are sized by this.
358 *
359 * punch_hole is optional - when close_range() is asked to unshare
360 * and close, we don't need to copy descriptors in that range, so
361 * a smaller cloned descriptor table might suffice if the last
362 * currently opened descriptor falls into that range.
363 */
sane_fdtable_size(struct fdtable * fdt,struct fd_range * punch_hole)364 static unsigned int sane_fdtable_size(struct fdtable *fdt, struct fd_range *punch_hole)
365 {
366 unsigned int last = find_last_bit(fdt->open_fds, fdt->max_fds);
367
368 if (last == fdt->max_fds)
369 return NR_OPEN_DEFAULT;
370 if (punch_hole && punch_hole->to >= last && punch_hole->from <= last) {
371 last = find_last_bit(fdt->open_fds, punch_hole->from);
372 if (last == punch_hole->from)
373 return NR_OPEN_DEFAULT;
374 }
375 return ALIGN(last + 1, BITS_PER_LONG);
376 }
377
378 /*
379 * Allocate a new descriptor table and copy contents from the passed in
380 * instance. Returns a pointer to cloned table on success, ERR_PTR()
381 * on failure. For 'punch_hole' see sane_fdtable_size().
382 */
dup_fd(struct files_struct * oldf,struct fd_range * punch_hole)383 struct files_struct *dup_fd(struct files_struct *oldf, struct fd_range *punch_hole)
384 {
385 struct files_struct *newf;
386 struct file **old_fds, **new_fds;
387 unsigned int open_files, i;
388 struct fdtable *old_fdt, *new_fdt;
389
390 newf = kmem_cache_alloc(files_cachep, GFP_KERNEL);
391 if (!newf)
392 return ERR_PTR(-ENOMEM);
393
394 atomic_set(&newf->count, 1);
395
396 spin_lock_init(&newf->file_lock);
397 newf->resize_in_progress = false;
398 init_waitqueue_head(&newf->resize_wait);
399 newf->next_fd = 0;
400 new_fdt = &newf->fdtab;
401 new_fdt->max_fds = NR_OPEN_DEFAULT;
402 new_fdt->close_on_exec = newf->close_on_exec_init;
403 new_fdt->open_fds = newf->open_fds_init;
404 new_fdt->full_fds_bits = newf->full_fds_bits_init;
405 new_fdt->fd = &newf->fd_array[0];
406
407 spin_lock(&oldf->file_lock);
408 old_fdt = files_fdtable(oldf);
409 open_files = sane_fdtable_size(old_fdt, punch_hole);
410
411 /*
412 * Check whether we need to allocate a larger fd array and fd set.
413 */
414 while (unlikely(open_files > new_fdt->max_fds)) {
415 spin_unlock(&oldf->file_lock);
416
417 if (new_fdt != &newf->fdtab)
418 __free_fdtable(new_fdt);
419
420 new_fdt = alloc_fdtable(open_files);
421 if (IS_ERR(new_fdt)) {
422 kmem_cache_free(files_cachep, newf);
423 return ERR_CAST(new_fdt);
424 }
425
426 /*
427 * Reacquire the oldf lock and a pointer to its fd table
428 * who knows it may have a new bigger fd table. We need
429 * the latest pointer.
430 */
431 spin_lock(&oldf->file_lock);
432 old_fdt = files_fdtable(oldf);
433 open_files = sane_fdtable_size(old_fdt, punch_hole);
434 }
435
436 copy_fd_bitmaps(new_fdt, old_fdt, open_files / BITS_PER_LONG);
437
438 old_fds = old_fdt->fd;
439 new_fds = new_fdt->fd;
440
441 /*
442 * We may be racing against fd allocation from other threads using this
443 * files_struct, despite holding ->file_lock.
444 *
445 * alloc_fd() might have already claimed a slot, while fd_install()
446 * did not populate it yet. Note the latter operates locklessly, so
447 * the file can show up as we are walking the array below.
448 *
449 * At the same time we know no files will disappear as all other
450 * operations take the lock.
451 *
452 * Instead of trying to placate userspace racing with itself, we
453 * ref the file if we see it and mark the fd slot as unused otherwise.
454 */
455 for (i = open_files; i != 0; i--) {
456 struct file *f = rcu_dereference_raw(*old_fds++);
457 if (f) {
458 get_file(f);
459 } else {
460 __clear_open_fd(open_files - i, new_fdt);
461 }
462 rcu_assign_pointer(*new_fds++, f);
463 }
464 spin_unlock(&oldf->file_lock);
465
466 /* clear the remainder */
467 memset(new_fds, 0, (new_fdt->max_fds - open_files) * sizeof(struct file *));
468
469 rcu_assign_pointer(newf->fdt, new_fdt);
470
471 return newf;
472 }
473
close_files(struct files_struct * files)474 static struct fdtable *close_files(struct files_struct * files)
475 {
476 /*
477 * It is safe to dereference the fd table without RCU or
478 * ->file_lock because this is the last reference to the
479 * files structure.
480 */
481 struct fdtable *fdt = rcu_dereference_raw(files->fdt);
482 unsigned int i, j = 0;
483
484 for (;;) {
485 unsigned long set;
486 i = j * BITS_PER_LONG;
487 if (i >= fdt->max_fds)
488 break;
489 set = fdt->open_fds[j++];
490 while (set) {
491 if (set & 1) {
492 struct file *file = fdt->fd[i];
493 if (file) {
494 filp_close(file, files);
495 cond_resched();
496 }
497 }
498 i++;
499 set >>= 1;
500 }
501 }
502
503 return fdt;
504 }
505
put_files_struct(struct files_struct * files)506 void put_files_struct(struct files_struct *files)
507 {
508 if (atomic_dec_and_test(&files->count)) {
509 struct fdtable *fdt = close_files(files);
510
511 /* free the arrays if they are not embedded */
512 if (fdt != &files->fdtab)
513 __free_fdtable(fdt);
514 kmem_cache_free(files_cachep, files);
515 }
516 }
517
exit_files(struct task_struct * tsk)518 void exit_files(struct task_struct *tsk)
519 {
520 struct files_struct * files = tsk->files;
521
522 if (files) {
523 task_lock(tsk);
524 tsk->files = NULL;
525 task_unlock(tsk);
526 put_files_struct(files);
527 }
528 }
529
530 struct files_struct init_files = {
531 .count = ATOMIC_INIT(1),
532 .fdt = &init_files.fdtab,
533 .fdtab = {
534 .max_fds = NR_OPEN_DEFAULT,
535 .fd = &init_files.fd_array[0],
536 .close_on_exec = init_files.close_on_exec_init,
537 .open_fds = init_files.open_fds_init,
538 .full_fds_bits = init_files.full_fds_bits_init,
539 },
540 .file_lock = __SPIN_LOCK_UNLOCKED(init_files.file_lock),
541 .resize_wait = __WAIT_QUEUE_HEAD_INITIALIZER(init_files.resize_wait),
542 };
543
find_next_fd(struct fdtable * fdt,unsigned int start)544 static unsigned int find_next_fd(struct fdtable *fdt, unsigned int start)
545 {
546 unsigned int maxfd = fdt->max_fds; /* always multiple of BITS_PER_LONG */
547 unsigned int maxbit = maxfd / BITS_PER_LONG;
548 unsigned int bitbit = start / BITS_PER_LONG;
549 unsigned int bit;
550
551 /*
552 * Try to avoid looking at the second level bitmap
553 */
554 bit = find_next_zero_bit(&fdt->open_fds[bitbit], BITS_PER_LONG,
555 start & (BITS_PER_LONG - 1));
556 if (bit < BITS_PER_LONG)
557 return bit + bitbit * BITS_PER_LONG;
558
559 bitbit = find_next_zero_bit(fdt->full_fds_bits, maxbit, bitbit) * BITS_PER_LONG;
560 if (bitbit >= maxfd)
561 return maxfd;
562 if (bitbit > start)
563 start = bitbit;
564 return find_next_zero_bit(fdt->open_fds, maxfd, start);
565 }
566
567 /*
568 * allocate a file descriptor, mark it busy.
569 */
alloc_fd(unsigned start,unsigned end,unsigned flags)570 static int alloc_fd(unsigned start, unsigned end, unsigned flags)
571 {
572 struct files_struct *files = current->files;
573 unsigned int fd;
574 int error;
575 struct fdtable *fdt;
576
577 spin_lock(&files->file_lock);
578 repeat:
579 fdt = files_fdtable(files);
580 fd = start;
581 if (fd < files->next_fd)
582 fd = files->next_fd;
583
584 if (likely(fd < fdt->max_fds))
585 fd = find_next_fd(fdt, fd);
586
587 /*
588 * N.B. For clone tasks sharing a files structure, this test
589 * will limit the total number of files that can be opened.
590 */
591 error = -EMFILE;
592 if (unlikely(fd >= end))
593 goto out;
594
595 if (unlikely(fd >= fdt->max_fds)) {
596 error = expand_files(files, fd);
597 if (error < 0)
598 goto out;
599
600 goto repeat;
601 }
602
603 if (start <= files->next_fd)
604 files->next_fd = fd + 1;
605
606 __set_open_fd(fd, fdt, flags & O_CLOEXEC);
607 error = fd;
608 VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
609
610 out:
611 spin_unlock(&files->file_lock);
612 return error;
613 }
614
__get_unused_fd_flags(unsigned flags,unsigned long nofile)615 int __get_unused_fd_flags(unsigned flags, unsigned long nofile)
616 {
617 return alloc_fd(0, nofile, flags);
618 }
619
get_unused_fd_flags(unsigned flags)620 int get_unused_fd_flags(unsigned flags)
621 {
622 return __get_unused_fd_flags(flags, rlimit(RLIMIT_NOFILE));
623 }
624 EXPORT_SYMBOL(get_unused_fd_flags);
625
__put_unused_fd(struct files_struct * files,unsigned int fd)626 static void __put_unused_fd(struct files_struct *files, unsigned int fd)
627 {
628 struct fdtable *fdt = files_fdtable(files);
629 __clear_open_fd(fd, fdt);
630 if (fd < files->next_fd)
631 files->next_fd = fd;
632 }
633
put_unused_fd(unsigned int fd)634 void put_unused_fd(unsigned int fd)
635 {
636 struct files_struct *files = current->files;
637 spin_lock(&files->file_lock);
638 __put_unused_fd(files, fd);
639 spin_unlock(&files->file_lock);
640 }
641
642 EXPORT_SYMBOL(put_unused_fd);
643
644 /*
645 * Install a file pointer in the fd array while it is being resized.
646 *
647 * We need to make sure our update to the array does not get lost as the resizing
648 * thread can be copying the content as we modify it.
649 *
650 * We have two ways to do it:
651 * - go off CPU waiting for resize_in_progress to clear
652 * - take the spin lock
653 *
654 * The latter is trivial to implement and saves us from having to might_sleep()
655 * for debugging purposes.
656 *
657 * This is moved out of line from fd_install() to convince gcc to optimize that
658 * routine better.
659 */
fd_install_slowpath(unsigned int fd,struct file * file)660 static void noinline fd_install_slowpath(unsigned int fd, struct file *file)
661 {
662 struct files_struct *files = current->files;
663 struct fdtable *fdt;
664
665 spin_lock(&files->file_lock);
666 fdt = files_fdtable(files);
667 VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
668 rcu_assign_pointer(fdt->fd[fd], file);
669 spin_unlock(&files->file_lock);
670 }
671
672 /**
673 * fd_install - install a file pointer in the fd array
674 * @fd: file descriptor to install the file in
675 * @file: the file to install
676 *
677 * This consumes the "file" refcount, so callers should treat it
678 * as if they had called fput(file).
679 */
fd_install(unsigned int fd,struct file * file)680 void fd_install(unsigned int fd, struct file *file)
681 {
682 struct files_struct *files = current->files;
683 struct fdtable *fdt;
684
685 if (WARN_ON_ONCE(unlikely(file->f_mode & FMODE_BACKING)))
686 return;
687
688 rcu_read_lock_sched();
689 if (unlikely(files->resize_in_progress)) {
690 rcu_read_unlock_sched();
691 fd_install_slowpath(fd, file);
692 return;
693 }
694 /* coupled with smp_wmb() in expand_fdtable() */
695 smp_rmb();
696 fdt = rcu_dereference_sched(files->fdt);
697 VFS_BUG_ON(rcu_access_pointer(fdt->fd[fd]) != NULL);
698 rcu_assign_pointer(fdt->fd[fd], file);
699 rcu_read_unlock_sched();
700 }
701
702 EXPORT_SYMBOL(fd_install);
703
704 /**
705 * file_close_fd_locked - return file associated with fd
706 * @files: file struct to retrieve file from
707 * @fd: file descriptor to retrieve file for
708 *
709 * Doesn't take a separate reference count.
710 *
711 * Context: files_lock must be held.
712 *
713 * Returns: The file associated with @fd (NULL if @fd is not open)
714 */
file_close_fd_locked(struct files_struct * files,unsigned fd)715 struct file *file_close_fd_locked(struct files_struct *files, unsigned fd)
716 {
717 struct fdtable *fdt = files_fdtable(files);
718 struct file *file;
719
720 lockdep_assert_held(&files->file_lock);
721
722 if (fd >= fdt->max_fds)
723 return NULL;
724
725 fd = array_index_nospec(fd, fdt->max_fds);
726 file = rcu_dereference_raw(fdt->fd[fd]);
727 if (file) {
728 rcu_assign_pointer(fdt->fd[fd], NULL);
729 __put_unused_fd(files, fd);
730 }
731 return file;
732 }
733
close_fd(unsigned fd)734 int close_fd(unsigned fd)
735 {
736 struct files_struct *files = current->files;
737 struct file *file;
738
739 spin_lock(&files->file_lock);
740 file = file_close_fd_locked(files, fd);
741 spin_unlock(&files->file_lock);
742 if (!file)
743 return -EBADF;
744
745 return filp_close(file, files);
746 }
747 EXPORT_SYMBOL(close_fd);
748
749 /**
750 * last_fd - return last valid index into fd table
751 * @fdt: File descriptor table.
752 *
753 * Context: Either rcu read lock or files_lock must be held.
754 *
755 * Returns: Last valid index into fdtable.
756 */
last_fd(struct fdtable * fdt)757 static inline unsigned last_fd(struct fdtable *fdt)
758 {
759 return fdt->max_fds - 1;
760 }
761
__range_cloexec(struct files_struct * cur_fds,unsigned int fd,unsigned int max_fd)762 static inline void __range_cloexec(struct files_struct *cur_fds,
763 unsigned int fd, unsigned int max_fd)
764 {
765 struct fdtable *fdt;
766
767 /* make sure we're using the correct maximum value */
768 spin_lock(&cur_fds->file_lock);
769 fdt = files_fdtable(cur_fds);
770 max_fd = min(last_fd(fdt), max_fd);
771 if (fd <= max_fd)
772 bitmap_set(fdt->close_on_exec, fd, max_fd - fd + 1);
773 spin_unlock(&cur_fds->file_lock);
774 }
775
__range_close(struct files_struct * files,unsigned int fd,unsigned int max_fd)776 static inline void __range_close(struct files_struct *files, unsigned int fd,
777 unsigned int max_fd)
778 {
779 struct file *file;
780 struct fdtable *fdt;
781 unsigned n;
782
783 spin_lock(&files->file_lock);
784 fdt = files_fdtable(files);
785 n = last_fd(fdt);
786 max_fd = min(max_fd, n);
787
788 for (fd = find_next_bit(fdt->open_fds, max_fd + 1, fd);
789 fd <= max_fd;
790 fd = find_next_bit(fdt->open_fds, max_fd + 1, fd + 1)) {
791 file = file_close_fd_locked(files, fd);
792 if (file) {
793 spin_unlock(&files->file_lock);
794 filp_close(file, files);
795 cond_resched();
796 spin_lock(&files->file_lock);
797 fdt = files_fdtable(files);
798 } else if (need_resched()) {
799 spin_unlock(&files->file_lock);
800 cond_resched();
801 spin_lock(&files->file_lock);
802 fdt = files_fdtable(files);
803 }
804 }
805 spin_unlock(&files->file_lock);
806 }
807
808 /**
809 * sys_close_range() - Close all file descriptors in a given range.
810 *
811 * @fd: starting file descriptor to close
812 * @max_fd: last file descriptor to close
813 * @flags: CLOSE_RANGE flags.
814 *
815 * This closes a range of file descriptors. All file descriptors
816 * from @fd up to and including @max_fd are closed.
817 * Currently, errors to close a given file descriptor are ignored.
818 */
SYSCALL_DEFINE3(close_range,unsigned int,fd,unsigned int,max_fd,unsigned int,flags)819 SYSCALL_DEFINE3(close_range, unsigned int, fd, unsigned int, max_fd,
820 unsigned int, flags)
821 {
822 struct task_struct *me = current;
823 struct files_struct *cur_fds = me->files, *fds = NULL;
824
825 if (flags & ~(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))
826 return -EINVAL;
827
828 if (fd > max_fd)
829 return -EINVAL;
830
831 if ((flags & CLOSE_RANGE_UNSHARE) && atomic_read(&cur_fds->count) > 1) {
832 struct fd_range range = {fd, max_fd}, *punch_hole = ⦥
833
834 /*
835 * If the caller requested all fds to be made cloexec we always
836 * copy all of the file descriptors since they still want to
837 * use them.
838 */
839 if (flags & CLOSE_RANGE_CLOEXEC)
840 punch_hole = NULL;
841
842 fds = dup_fd(cur_fds, punch_hole);
843 if (IS_ERR(fds))
844 return PTR_ERR(fds);
845 /*
846 * We used to share our file descriptor table, and have now
847 * created a private one, make sure we're using it below.
848 */
849 swap(cur_fds, fds);
850 }
851
852 if (flags & CLOSE_RANGE_CLOEXEC)
853 __range_cloexec(cur_fds, fd, max_fd);
854 else
855 __range_close(cur_fds, fd, max_fd);
856
857 if (fds) {
858 /*
859 * We're done closing the files we were supposed to. Time to install
860 * the new file descriptor table and drop the old one.
861 */
862 task_lock(me);
863 me->files = cur_fds;
864 task_unlock(me);
865 put_files_struct(fds);
866 }
867
868 return 0;
869 }
870
871 /**
872 * file_close_fd - return file associated with fd
873 * @fd: file descriptor to retrieve file for
874 *
875 * Doesn't take a separate reference count.
876 *
877 * Returns: The file associated with @fd (NULL if @fd is not open)
878 */
file_close_fd(unsigned int fd)879 struct file *file_close_fd(unsigned int fd)
880 {
881 struct files_struct *files = current->files;
882 struct file *file;
883
884 spin_lock(&files->file_lock);
885 file = file_close_fd_locked(files, fd);
886 spin_unlock(&files->file_lock);
887
888 return file;
889 }
890
do_close_on_exec(struct files_struct * files)891 void do_close_on_exec(struct files_struct *files)
892 {
893 unsigned i;
894 struct fdtable *fdt;
895
896 /* exec unshares first */
897 spin_lock(&files->file_lock);
898 for (i = 0; ; i++) {
899 unsigned long set;
900 unsigned fd = i * BITS_PER_LONG;
901 fdt = files_fdtable(files);
902 if (fd >= fdt->max_fds)
903 break;
904 set = fdt->close_on_exec[i];
905 if (!set)
906 continue;
907 fdt->close_on_exec[i] = 0;
908 for ( ; set ; fd++, set >>= 1) {
909 struct file *file;
910 if (!(set & 1))
911 continue;
912 file = fdt->fd[fd];
913 if (!file)
914 continue;
915 rcu_assign_pointer(fdt->fd[fd], NULL);
916 __put_unused_fd(files, fd);
917 spin_unlock(&files->file_lock);
918 filp_close(file, files);
919 cond_resched();
920 spin_lock(&files->file_lock);
921 }
922
923 }
924 spin_unlock(&files->file_lock);
925 }
926
__get_file_rcu(struct file __rcu ** f)927 static struct file *__get_file_rcu(struct file __rcu **f)
928 {
929 struct file __rcu *file;
930 struct file __rcu *file_reloaded;
931 struct file __rcu *file_reloaded_cmp;
932
933 file = rcu_dereference_raw(*f);
934 if (!file)
935 return NULL;
936
937 if (unlikely(!file_ref_get(&file->f_ref)))
938 return ERR_PTR(-EAGAIN);
939
940 file_reloaded = rcu_dereference_raw(*f);
941
942 /*
943 * Ensure that all accesses have a dependency on the load from
944 * rcu_dereference_raw() above so we get correct ordering
945 * between reuse/allocation and the pointer check below.
946 */
947 file_reloaded_cmp = file_reloaded;
948 OPTIMIZER_HIDE_VAR(file_reloaded_cmp);
949
950 /*
951 * file_ref_get() above provided a full memory barrier when we
952 * acquired a reference.
953 *
954 * This is paired with the write barrier from assigning to the
955 * __rcu protected file pointer so that if that pointer still
956 * matches the current file, we know we have successfully
957 * acquired a reference to the right file.
958 *
959 * If the pointers don't match the file has been reallocated by
960 * SLAB_TYPESAFE_BY_RCU.
961 */
962 if (file == file_reloaded_cmp)
963 return file_reloaded;
964
965 fput(file);
966 return ERR_PTR(-EAGAIN);
967 }
968
969 /**
970 * get_file_rcu - try go get a reference to a file under rcu
971 * @f: the file to get a reference on
972 *
973 * This function tries to get a reference on @f carefully verifying that
974 * @f hasn't been reused.
975 *
976 * This function should rarely have to be used and only by users who
977 * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
978 *
979 * Return: Returns @f with the reference count increased or NULL.
980 */
get_file_rcu(struct file __rcu ** f)981 struct file *get_file_rcu(struct file __rcu **f)
982 {
983 for (;;) {
984 struct file __rcu *file;
985
986 file = __get_file_rcu(f);
987 if (!IS_ERR(file))
988 return file;
989 }
990 }
991 EXPORT_SYMBOL_GPL(get_file_rcu);
992
993 /**
994 * get_file_active - try go get a reference to a file
995 * @f: the file to get a reference on
996 *
997 * In contast to get_file_rcu() the pointer itself isn't part of the
998 * reference counting.
999 *
1000 * This function should rarely have to be used and only by users who
1001 * understand the implications of SLAB_TYPESAFE_BY_RCU. Try to avoid it.
1002 *
1003 * Return: Returns @f with the reference count increased or NULL.
1004 */
get_file_active(struct file ** f)1005 struct file *get_file_active(struct file **f)
1006 {
1007 struct file __rcu *file;
1008
1009 rcu_read_lock();
1010 file = __get_file_rcu(f);
1011 rcu_read_unlock();
1012 if (IS_ERR(file))
1013 file = NULL;
1014 return file;
1015 }
1016 EXPORT_SYMBOL_GPL(get_file_active);
1017
__fget_files_rcu(struct files_struct * files,unsigned int fd,fmode_t mask)1018 static inline struct file *__fget_files_rcu(struct files_struct *files,
1019 unsigned int fd, fmode_t mask)
1020 {
1021 for (;;) {
1022 struct file *file;
1023 struct fdtable *fdt = rcu_dereference_raw(files->fdt);
1024 struct file __rcu **fdentry;
1025 unsigned long nospec_mask;
1026
1027 /* Mask is a 0 for invalid fd's, ~0 for valid ones */
1028 nospec_mask = array_index_mask_nospec(fd, fdt->max_fds);
1029
1030 /*
1031 * fdentry points to the 'fd' offset, or fdt->fd[0].
1032 * Loading from fdt->fd[0] is always safe, because the
1033 * array always exists.
1034 */
1035 fdentry = fdt->fd + (fd & nospec_mask);
1036
1037 /* Do the load, then mask any invalid result */
1038 file = rcu_dereference_raw(*fdentry);
1039 file = (void *)(nospec_mask & (unsigned long)file);
1040 if (unlikely(!file))
1041 return NULL;
1042
1043 /*
1044 * Ok, we have a file pointer that was valid at
1045 * some point, but it might have become stale since.
1046 *
1047 * We need to confirm it by incrementing the refcount
1048 * and then check the lookup again.
1049 *
1050 * file_ref_get() gives us a full memory barrier. We
1051 * only really need an 'acquire' one to protect the
1052 * loads below, but we don't have that.
1053 */
1054 if (unlikely(!file_ref_get(&file->f_ref)))
1055 continue;
1056
1057 /*
1058 * Such a race can take two forms:
1059 *
1060 * (a) the file ref already went down to zero and the
1061 * file hasn't been reused yet or the file count
1062 * isn't zero but the file has already been reused.
1063 *
1064 * (b) the file table entry has changed under us.
1065 * Note that we don't need to re-check the 'fdt->fd'
1066 * pointer having changed, because it always goes
1067 * hand-in-hand with 'fdt'.
1068 *
1069 * If so, we need to put our ref and try again.
1070 */
1071 if (unlikely(file != rcu_dereference_raw(*fdentry)) ||
1072 unlikely(rcu_dereference_raw(files->fdt) != fdt)) {
1073 fput(file);
1074 continue;
1075 }
1076
1077 /*
1078 * This isn't the file we're looking for or we're not
1079 * allowed to get a reference to it.
1080 */
1081 if (unlikely(file->f_mode & mask)) {
1082 fput(file);
1083 return NULL;
1084 }
1085
1086 /*
1087 * Ok, we have a ref to the file, and checked that it
1088 * still exists.
1089 */
1090 return file;
1091 }
1092 }
1093
__fget_files(struct files_struct * files,unsigned int fd,fmode_t mask)1094 static struct file *__fget_files(struct files_struct *files, unsigned int fd,
1095 fmode_t mask)
1096 {
1097 struct file *file;
1098
1099 rcu_read_lock();
1100 file = __fget_files_rcu(files, fd, mask);
1101 rcu_read_unlock();
1102
1103 return file;
1104 }
1105
__fget(unsigned int fd,fmode_t mask)1106 static inline struct file *__fget(unsigned int fd, fmode_t mask)
1107 {
1108 return __fget_files(current->files, fd, mask);
1109 }
1110
fget(unsigned int fd)1111 struct file *fget(unsigned int fd)
1112 {
1113 return __fget(fd, FMODE_PATH);
1114 }
1115 EXPORT_SYMBOL(fget);
1116
fget_raw(unsigned int fd)1117 struct file *fget_raw(unsigned int fd)
1118 {
1119 return __fget(fd, 0);
1120 }
1121 EXPORT_SYMBOL(fget_raw);
1122
fget_task(struct task_struct * task,unsigned int fd)1123 struct file *fget_task(struct task_struct *task, unsigned int fd)
1124 {
1125 struct file *file = NULL;
1126
1127 task_lock(task);
1128 if (task->files)
1129 file = __fget_files(task->files, fd, 0);
1130 task_unlock(task);
1131
1132 return file;
1133 }
1134
fget_task_next(struct task_struct * task,unsigned int * ret_fd)1135 struct file *fget_task_next(struct task_struct *task, unsigned int *ret_fd)
1136 {
1137 /* Must be called with rcu_read_lock held */
1138 struct files_struct *files;
1139 unsigned int fd = *ret_fd;
1140 struct file *file = NULL;
1141
1142 task_lock(task);
1143 files = task->files;
1144 if (files) {
1145 rcu_read_lock();
1146 for (; fd < files_fdtable(files)->max_fds; fd++) {
1147 file = __fget_files_rcu(files, fd, 0);
1148 if (file)
1149 break;
1150 }
1151 rcu_read_unlock();
1152 }
1153 task_unlock(task);
1154 *ret_fd = fd;
1155 return file;
1156 }
1157 EXPORT_SYMBOL(fget_task_next);
1158
1159 /*
1160 * Lightweight file lookup - no refcnt increment if fd table isn't shared.
1161 *
1162 * You can use this instead of fget if you satisfy all of the following
1163 * conditions:
1164 * 1) You must call fput_light before exiting the syscall and returning control
1165 * to userspace (i.e. you cannot remember the returned struct file * after
1166 * returning to userspace).
1167 * 2) You must not call filp_close on the returned struct file * in between
1168 * calls to fget_light and fput_light.
1169 * 3) You must not clone the current task in between the calls to fget_light
1170 * and fput_light.
1171 *
1172 * The fput_needed flag returned by fget_light should be passed to the
1173 * corresponding fput_light.
1174 *
1175 * (As an exception to rule 2, you can call filp_close between fget_light and
1176 * fput_light provided that you capture a real refcount with get_file before
1177 * the call to filp_close, and ensure that this real refcount is fput *after*
1178 * the fput_light call.)
1179 *
1180 * See also the documentation in rust/kernel/file.rs.
1181 */
__fget_light(unsigned int fd,fmode_t mask)1182 static inline struct fd __fget_light(unsigned int fd, fmode_t mask)
1183 {
1184 struct files_struct *files = current->files;
1185 struct file *file;
1186
1187 /*
1188 * If another thread is concurrently calling close_fd() followed
1189 * by put_files_struct(), we must not observe the old table
1190 * entry combined with the new refcount - otherwise we could
1191 * return a file that is concurrently being freed.
1192 *
1193 * atomic_read_acquire() pairs with atomic_dec_and_test() in
1194 * put_files_struct().
1195 */
1196 if (likely(atomic_read_acquire(&files->count) == 1)) {
1197 file = files_lookup_fd_raw(files, fd);
1198 if (!file || unlikely(file->f_mode & mask))
1199 return EMPTY_FD;
1200 return BORROWED_FD(file);
1201 } else {
1202 file = __fget_files(files, fd, mask);
1203 if (!file)
1204 return EMPTY_FD;
1205 return CLONED_FD(file);
1206 }
1207 }
fdget(unsigned int fd)1208 struct fd fdget(unsigned int fd)
1209 {
1210 return __fget_light(fd, FMODE_PATH);
1211 }
1212 EXPORT_SYMBOL(fdget);
1213
fdget_raw(unsigned int fd)1214 struct fd fdget_raw(unsigned int fd)
1215 {
1216 return __fget_light(fd, 0);
1217 }
1218
1219 /*
1220 * Try to avoid f_pos locking. We only need it if the
1221 * file is marked for FMODE_ATOMIC_POS, and it can be
1222 * accessed multiple ways.
1223 *
1224 * Always do it for directories, because pidfd_getfd()
1225 * can make a file accessible even if it otherwise would
1226 * not be, and for directories this is a correctness
1227 * issue, not a "POSIX requirement".
1228 */
file_needs_f_pos_lock(struct file * file)1229 static inline bool file_needs_f_pos_lock(struct file *file)
1230 {
1231 if (!(file->f_mode & FMODE_ATOMIC_POS))
1232 return false;
1233 if (__file_ref_read_raw(&file->f_ref) != FILE_REF_ONEREF)
1234 return true;
1235 if (file->f_op->iterate_shared)
1236 return true;
1237 return false;
1238 }
1239
file_seek_cur_needs_f_lock(struct file * file)1240 bool file_seek_cur_needs_f_lock(struct file *file)
1241 {
1242 if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared)
1243 return false;
1244
1245 /*
1246 * Note that we are not guaranteed to be called after fdget_pos() on
1247 * this file obj, in which case the caller is expected to provide the
1248 * appropriate locking.
1249 */
1250
1251 return true;
1252 }
1253
fdget_pos(unsigned int fd)1254 struct fd fdget_pos(unsigned int fd)
1255 {
1256 struct fd f = fdget(fd);
1257 struct file *file = fd_file(f);
1258
1259 if (likely(file) && file_needs_f_pos_lock(file)) {
1260 f.word |= FDPUT_POS_UNLOCK;
1261 mutex_lock(&file->f_pos_lock);
1262 }
1263 return f;
1264 }
1265
__f_unlock_pos(struct file * f)1266 void __f_unlock_pos(struct file *f)
1267 {
1268 mutex_unlock(&f->f_pos_lock);
1269 }
1270
1271 /*
1272 * We only lock f_pos if we have threads or if the file might be
1273 * shared with another process. In both cases we'll have an elevated
1274 * file count (done either by fdget() or by fork()).
1275 */
1276
set_close_on_exec(unsigned int fd,int flag)1277 void set_close_on_exec(unsigned int fd, int flag)
1278 {
1279 struct files_struct *files = current->files;
1280 spin_lock(&files->file_lock);
1281 __set_close_on_exec(fd, files_fdtable(files), flag);
1282 spin_unlock(&files->file_lock);
1283 }
1284
get_close_on_exec(unsigned int fd)1285 bool get_close_on_exec(unsigned int fd)
1286 {
1287 bool res;
1288 rcu_read_lock();
1289 res = close_on_exec(fd, current->files);
1290 rcu_read_unlock();
1291 return res;
1292 }
1293
do_dup2(struct files_struct * files,struct file * file,unsigned fd,unsigned flags)1294 static int do_dup2(struct files_struct *files,
1295 struct file *file, unsigned fd, unsigned flags)
1296 __releases(&files->file_lock)
1297 {
1298 struct file *tofree;
1299 struct fdtable *fdt;
1300
1301 /*
1302 * dup2() is expected to close the file installed in the target fd slot
1303 * (if any). However, userspace hand-picking a fd may be racing against
1304 * its own threads which happened to allocate it in open() et al but did
1305 * not populate it yet.
1306 *
1307 * Broadly speaking we may be racing against the following:
1308 * fd = get_unused_fd_flags(); // fd slot reserved, ->fd[fd] == NULL
1309 * file = hard_work_goes_here();
1310 * fd_install(fd, file); // only now ->fd[fd] == file
1311 *
1312 * It is an invariant that a successfully allocated fd has a NULL entry
1313 * in the array until the matching fd_install().
1314 *
1315 * If we fit the window, we have the fd to populate, yet no target file
1316 * to close. Trying to ignore it and install our new file would violate
1317 * the invariant and make fd_install() overwrite our file.
1318 *
1319 * Things can be done(tm) to handle this. However, the issue does not
1320 * concern legitimate programs and we only need to make sure the kernel
1321 * does not trip over it.
1322 *
1323 * The simplest way out is to return an error if we find ourselves here.
1324 *
1325 * POSIX is silent on the issue, we return -EBUSY.
1326 */
1327 fdt = files_fdtable(files);
1328 fd = array_index_nospec(fd, fdt->max_fds);
1329 tofree = rcu_dereference_raw(fdt->fd[fd]);
1330 if (!tofree && fd_is_open(fd, fdt))
1331 goto Ebusy;
1332 get_file(file);
1333 rcu_assign_pointer(fdt->fd[fd], file);
1334 __set_open_fd(fd, fdt, flags & O_CLOEXEC);
1335 spin_unlock(&files->file_lock);
1336
1337 if (tofree)
1338 filp_close(tofree, files);
1339
1340 return fd;
1341
1342 Ebusy:
1343 spin_unlock(&files->file_lock);
1344 return -EBUSY;
1345 }
1346
replace_fd(unsigned fd,struct file * file,unsigned flags)1347 int replace_fd(unsigned fd, struct file *file, unsigned flags)
1348 {
1349 int err;
1350 struct files_struct *files = current->files;
1351
1352 if (!file)
1353 return close_fd(fd);
1354
1355 if (fd >= rlimit(RLIMIT_NOFILE))
1356 return -EBADF;
1357
1358 spin_lock(&files->file_lock);
1359 err = expand_files(files, fd);
1360 if (unlikely(err < 0))
1361 goto out_unlock;
1362 err = do_dup2(files, file, fd, flags);
1363 if (err < 0)
1364 return err;
1365 return 0;
1366
1367 out_unlock:
1368 spin_unlock(&files->file_lock);
1369 return err;
1370 }
1371
1372 /**
1373 * receive_fd() - Install received file into file descriptor table
1374 * @file: struct file that was received from another process
1375 * @ufd: __user pointer to write new fd number to
1376 * @o_flags: the O_* flags to apply to the new fd entry
1377 *
1378 * Installs a received file into the file descriptor table, with appropriate
1379 * checks and count updates. Optionally writes the fd number to userspace, if
1380 * @ufd is non-NULL.
1381 *
1382 * This helper handles its own reference counting of the incoming
1383 * struct file.
1384 *
1385 * Returns newly install fd or -ve on error.
1386 */
receive_fd(struct file * file,int __user * ufd,unsigned int o_flags)1387 int receive_fd(struct file *file, int __user *ufd, unsigned int o_flags)
1388 {
1389 int error;
1390
1391 error = security_file_receive(file);
1392 if (error)
1393 return error;
1394
1395 FD_PREPARE(fdf, o_flags, file);
1396 if (fdf.err)
1397 return fdf.err;
1398 get_file(file);
1399
1400 if (ufd) {
1401 error = put_user(fd_prepare_fd(fdf), ufd);
1402 if (error)
1403 return error;
1404 }
1405
1406 __receive_sock(fd_prepare_file(fdf));
1407 return fd_publish(fdf);
1408 }
1409 EXPORT_SYMBOL_GPL(receive_fd);
1410
receive_fd_replace(int new_fd,struct file * file,unsigned int o_flags)1411 int receive_fd_replace(int new_fd, struct file *file, unsigned int o_flags)
1412 {
1413 int error;
1414
1415 error = security_file_receive(file);
1416 if (error)
1417 return error;
1418 error = replace_fd(new_fd, file, o_flags);
1419 if (error)
1420 return error;
1421 __receive_sock(file);
1422 return new_fd;
1423 }
1424
ksys_dup3(unsigned int oldfd,unsigned int newfd,int flags)1425 static int ksys_dup3(unsigned int oldfd, unsigned int newfd, int flags)
1426 {
1427 int err = -EBADF;
1428 struct file *file;
1429 struct files_struct *files = current->files;
1430
1431 if ((flags & ~O_CLOEXEC) != 0)
1432 return -EINVAL;
1433
1434 if (unlikely(oldfd == newfd))
1435 return -EINVAL;
1436
1437 if (newfd >= rlimit(RLIMIT_NOFILE))
1438 return -EBADF;
1439
1440 spin_lock(&files->file_lock);
1441 err = expand_files(files, newfd);
1442 file = files_lookup_fd_locked(files, oldfd);
1443 if (unlikely(!file))
1444 goto Ebadf;
1445 if (unlikely(err < 0)) {
1446 if (err == -EMFILE)
1447 goto Ebadf;
1448 goto out_unlock;
1449 }
1450 return do_dup2(files, file, newfd, flags);
1451
1452 Ebadf:
1453 err = -EBADF;
1454 out_unlock:
1455 spin_unlock(&files->file_lock);
1456 return err;
1457 }
1458
SYSCALL_DEFINE3(dup3,unsigned int,oldfd,unsigned int,newfd,int,flags)1459 SYSCALL_DEFINE3(dup3, unsigned int, oldfd, unsigned int, newfd, int, flags)
1460 {
1461 return ksys_dup3(oldfd, newfd, flags);
1462 }
1463
SYSCALL_DEFINE2(dup2,unsigned int,oldfd,unsigned int,newfd)1464 SYSCALL_DEFINE2(dup2, unsigned int, oldfd, unsigned int, newfd)
1465 {
1466 if (unlikely(newfd == oldfd)) { /* corner case */
1467 struct files_struct *files = current->files;
1468 struct file *f;
1469 int retval = oldfd;
1470
1471 rcu_read_lock();
1472 f = __fget_files_rcu(files, oldfd, 0);
1473 if (!f)
1474 retval = -EBADF;
1475 rcu_read_unlock();
1476 if (f)
1477 fput(f);
1478 return retval;
1479 }
1480 return ksys_dup3(oldfd, newfd, 0);
1481 }
1482
SYSCALL_DEFINE1(dup,unsigned int,fildes)1483 SYSCALL_DEFINE1(dup, unsigned int, fildes)
1484 {
1485 int ret = -EBADF;
1486 struct file *file = fget_raw(fildes);
1487
1488 if (file) {
1489 ret = get_unused_fd_flags(0);
1490 if (ret >= 0)
1491 fd_install(ret, file);
1492 else
1493 fput(file);
1494 }
1495 return ret;
1496 }
1497
f_dupfd(unsigned int from,struct file * file,unsigned flags)1498 int f_dupfd(unsigned int from, struct file *file, unsigned flags)
1499 {
1500 unsigned long nofile = rlimit(RLIMIT_NOFILE);
1501 int err;
1502 if (from >= nofile)
1503 return -EINVAL;
1504 err = alloc_fd(from, nofile, flags);
1505 if (err >= 0) {
1506 get_file(file);
1507 fd_install(err, file);
1508 }
1509 return err;
1510 }
1511
iterate_fd(struct files_struct * files,unsigned n,int (* f)(const void *,struct file *,unsigned),const void * p)1512 int iterate_fd(struct files_struct *files, unsigned n,
1513 int (*f)(const void *, struct file *, unsigned),
1514 const void *p)
1515 {
1516 struct fdtable *fdt;
1517 int res = 0;
1518 if (!files)
1519 return 0;
1520 spin_lock(&files->file_lock);
1521 for (fdt = files_fdtable(files); n < fdt->max_fds; n++) {
1522 struct file *file;
1523 file = rcu_dereference_check_fdtable(files, fdt->fd[n]);
1524 if (!file)
1525 continue;
1526 res = f(p, file, n);
1527 if (res)
1528 break;
1529 }
1530 spin_unlock(&files->file_lock);
1531 return res;
1532 }
1533 EXPORT_SYMBOL(iterate_fd);
1534