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