2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
44 #include "opt_ktrace.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capsicum.h>
51 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
56 #include <sys/kernel.h>
57 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/selinfo.h>
66 #include <sys/protosw.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
70 #include <sys/signalvar.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysproto.h>
78 #include <sys/unistd.h>
80 #include <sys/vnode.h>
82 #include <sys/ktrace.h>
87 #include <security/audit/audit.h>
94 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
95 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
96 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
97 "file desc to leader structures");
98 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
99 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
101 MALLOC_DECLARE(M_FADVISE);
103 static __read_mostly uma_zone_t file_zone;
104 static __read_mostly uma_zone_t filedesc0_zone;
105 static __read_mostly uma_zone_t pwd_zone;
106 static __read_mostly smr_t pwd_smr;
108 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
109 struct thread *td, int holdleaders);
110 static int fd_first_free(struct filedesc *fdp, int low, int size);
111 static int fd_last_used(struct filedesc *fdp, int size);
112 static void fdgrowtable(struct filedesc *fdp, int nfd);
113 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
114 static void fdunused(struct filedesc *fdp, int fd);
115 static void fdused(struct filedesc *fdp, int fd);
116 static int getmaxfd(struct thread *td);
117 static u_long *filecaps_copy_prep(const struct filecaps *src);
118 static void filecaps_copy_finish(const struct filecaps *src,
119 struct filecaps *dst, u_long *ioctls);
120 static u_long *filecaps_free_prep(struct filecaps *fcaps);
121 static void filecaps_free_finish(u_long *ioctls);
123 static struct pwd *pwd_alloc(void);
128 * - An array of open file descriptors (fd_ofiles)
129 * - An array of file flags (fd_ofileflags)
130 * - A bitmap recording which descriptors are in use (fd_map)
132 * A process starts out with NDFILE descriptors. The value of NDFILE has
133 * been selected based the historical limit of 20 open files, and an
134 * assumption that the majority of processes, especially short-lived
135 * processes like shells, will never need more.
137 * If this initial allocation is exhausted, a larger descriptor table and
138 * map are allocated dynamically, and the pointers in the process's struct
139 * filedesc are updated to point to those. This is repeated every time
140 * the process runs out of file descriptors (provided it hasn't hit its
143 * Since threads may hold references to individual descriptor table
144 * entries, the tables are never freed. Instead, they are placed on a
145 * linked list and freed only when the struct filedesc is released.
148 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
149 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
150 #define NDSLOT(x) ((x) / NDENTRIES)
151 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
152 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
155 * SLIST entry used to keep track of ofiles which must be reclaimed when
159 struct fdescenttbl *ft_table;
160 SLIST_ENTRY(freetable) ft_next;
164 * Initial allocation: a filedesc structure + the head of SLIST used to
165 * keep track of old ofiles + enough space for NDFILE descriptors.
168 struct fdescenttbl0 {
170 struct filedescent fdt_ofiles[NDFILE];
174 struct filedesc fd_fd;
175 SLIST_HEAD(, freetable) fd_free;
176 struct fdescenttbl0 fd_dfiles;
177 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
181 * Descriptor management.
183 static int __exclusive_cache_line openfiles; /* actual number of open files */
184 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
185 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
188 * If low >= size, just return low. Otherwise find the first zero bit in the
189 * given bitmap, starting at low and not exceeding size - 1. Return size if
193 fd_first_free(struct filedesc *fdp, int low, int size)
195 NDSLOTTYPE *map = fdp->fd_map;
203 if (low % NDENTRIES) {
204 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
205 if ((mask &= ~map[off]) != 0UL)
206 return (off * NDENTRIES + ffsl(mask) - 1);
209 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
210 if (map[off] != ~0UL)
211 return (off * NDENTRIES + ffsl(~map[off]) - 1);
216 * Find the highest non-zero bit in the given bitmap, starting at 0 and
217 * not exceeding size - 1. Return -1 if not found.
220 fd_last_used(struct filedesc *fdp, int size)
222 NDSLOTTYPE *map = fdp->fd_map;
227 if (size % NDENTRIES) {
228 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
229 if ((mask &= map[off]) != 0)
230 return (off * NDENTRIES + flsl(mask) - 1);
233 for (minoff = NDSLOT(0); off >= minoff; --off)
235 return (off * NDENTRIES + flsl(map[off]) - 1);
240 fdisused(struct filedesc *fdp, int fd)
243 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
244 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
246 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
250 * Mark a file descriptor as used.
253 fdused_init(struct filedesc *fdp, int fd)
256 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
258 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
262 fdused(struct filedesc *fdp, int fd)
265 FILEDESC_XLOCK_ASSERT(fdp);
267 fdused_init(fdp, fd);
268 if (fd > fdp->fd_lastfile)
269 fdp->fd_lastfile = fd;
270 if (fd == fdp->fd_freefile)
275 * Mark a file descriptor as unused.
278 fdunused(struct filedesc *fdp, int fd)
281 FILEDESC_XLOCK_ASSERT(fdp);
283 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
284 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
285 ("fd=%d is still in use", fd));
287 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288 if (fd < fdp->fd_freefile)
289 fdp->fd_freefile = fd;
290 if (fd == fdp->fd_lastfile)
291 fdp->fd_lastfile = fd_last_used(fdp, fd);
295 * Free a file descriptor.
297 * Avoid some work if fdp is about to be destroyed.
300 fdefree_last(struct filedescent *fde)
303 filecaps_free(&fde->fde_caps);
307 fdfree(struct filedesc *fdp, int fd)
309 struct filedescent *fde;
311 fde = &fdp->fd_ofiles[fd];
313 seqc_write_begin(&fde->fde_seqc);
315 fde->fde_file = NULL;
317 seqc_write_end(&fde->fde_seqc);
324 * System calls on descriptors.
326 #ifndef _SYS_SYSPROTO_H_
327 struct getdtablesize_args {
333 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
339 td->td_retval[0] = getmaxfd(td);
341 PROC_LOCK(td->td_proc);
342 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
343 PROC_UNLOCK(td->td_proc);
344 if (lim < td->td_retval[0])
345 td->td_retval[0] = lim;
351 * Duplicate a file descriptor to a particular value.
353 * Note: keep in mind that a potential race condition exists when closing
354 * descriptors from a shared descriptor table (via rfork).
356 #ifndef _SYS_SYSPROTO_H_
364 sys_dup2(struct thread *td, struct dup2_args *uap)
367 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
371 * Duplicate a file descriptor.
373 #ifndef _SYS_SYSPROTO_H_
380 sys_dup(struct thread *td, struct dup_args *uap)
383 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
387 * The file control system call.
389 #ifndef _SYS_SYSPROTO_H_
398 sys_fcntl(struct thread *td, struct fcntl_args *uap)
401 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
405 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
419 * Convert old flock structure to new.
421 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
422 fl.l_start = ofl.l_start;
423 fl.l_len = ofl.l_len;
424 fl.l_pid = ofl.l_pid;
425 fl.l_type = ofl.l_type;
426 fl.l_whence = ofl.l_whence;
440 arg1 = (intptr_t)&fl;
446 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
447 arg1 = (intptr_t)&fl;
455 error = kern_fcntl(td, fd, newcmd, arg1);
458 if (cmd == F_OGETLK) {
459 ofl.l_start = fl.l_start;
460 ofl.l_len = fl.l_len;
461 ofl.l_pid = fl.l_pid;
462 ofl.l_type = fl.l_type;
463 ofl.l_whence = fl.l_whence;
464 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
465 } else if (cmd == F_GETLK) {
466 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
472 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
474 struct filedesc *fdp;
476 struct file *fp, *fp2;
477 struct filedescent *fde;
481 int error, flg, seals, tmp;
495 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
498 case F_DUPFD_CLOEXEC:
500 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
505 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
508 case F_DUP2FD_CLOEXEC:
510 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
516 fde = fdeget_locked(fdp, fd);
519 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
522 FILEDESC_SUNLOCK(fdp);
528 fde = fdeget_locked(fdp, fd);
530 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
531 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
534 FILEDESC_XUNLOCK(fdp);
538 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
541 td->td_retval[0] = OFLAGS(fp->f_flag);
546 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
550 tmp = flg = fp->f_flag;
552 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
553 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
554 tmp = fp->f_flag & FNONBLOCK;
555 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
560 tmp = fp->f_flag & FASYNC;
561 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
566 atomic_clear_int(&fp->f_flag, FNONBLOCK);
568 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
573 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
576 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
578 td->td_retval[0] = tmp;
583 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
587 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
592 error = priv_check(td, PRIV_NFS_LOCKD);
600 /* FALLTHROUGH F_SETLK */
604 flp = (struct flock *)arg;
605 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
610 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
613 if (fp->f_type != DTYPE_VNODE) {
619 if (flp->l_whence == SEEK_CUR) {
620 foffset = foffset_get(fp);
623 foffset > OFF_MAX - flp->l_start)) {
628 flp->l_start += foffset;
632 switch (flp->l_type) {
634 if ((fp->f_flag & FREAD) == 0) {
638 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
639 PROC_LOCK(p->p_leader);
640 p->p_leader->p_flag |= P_ADVLOCK;
641 PROC_UNLOCK(p->p_leader);
643 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
647 if ((fp->f_flag & FWRITE) == 0) {
651 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
652 PROC_LOCK(p->p_leader);
653 p->p_leader->p_flag |= P_ADVLOCK;
654 PROC_UNLOCK(p->p_leader);
656 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
664 if (flg != F_REMOTE) {
668 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
669 F_UNLCKSYS, flp, flg);
675 if (error != 0 || flp->l_type == F_UNLCK ||
676 flp->l_type == F_UNLCKSYS) {
682 * Check for a race with close.
684 * The vnode is now advisory locked (or unlocked, but this case
685 * is not really important) as the caller requested.
686 * We had to drop the filedesc lock, so we need to recheck if
687 * the descriptor is still valid, because if it was closed
688 * in the meantime we need to remove advisory lock from the
689 * vnode - close on any descriptor leading to an advisory
690 * locked vnode, removes that lock.
691 * We will return 0 on purpose in that case, as the result of
692 * successful advisory lock might have been externally visible
693 * already. This is fine - effectively we pretend to the caller
694 * that the closing thread was a bit slower and that the
695 * advisory lock succeeded before the close.
697 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
703 flp->l_whence = SEEK_SET;
706 flp->l_type = F_UNLCK;
707 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708 F_UNLCK, flp, F_POSIX);
715 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
718 if (fp->f_type != DTYPE_VNODE) {
723 flp = (struct flock *)arg;
724 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
725 flp->l_type != F_UNLCK) {
730 if (flp->l_whence == SEEK_CUR) {
731 foffset = foffset_get(fp);
732 if ((flp->l_start > 0 &&
733 foffset > OFF_MAX - flp->l_start) ||
735 foffset < OFF_MIN - flp->l_start)) {
740 flp->l_start += foffset;
743 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
749 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
752 error = fo_add_seals(fp, arg);
757 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
760 if (fo_get_seals(fp, &seals) == 0)
761 td->td_retval[0] = seals;
768 arg = arg ? 128 * 1024: 0;
771 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
774 if (fp->f_type != DTYPE_VNODE) {
780 if (vp->v_type != VREG) {
787 * Exclusive lock synchronizes against f_seqcount reads and
788 * writes in sequential_heuristic().
790 error = vn_lock(vp, LK_EXCLUSIVE);
796 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
797 arg = MIN(arg, INT_MAX - bsize + 1);
798 fp->f_seqcount = MIN(IO_SEQMAX,
799 (arg + bsize - 1) / bsize);
800 atomic_set_int(&fp->f_flag, FRDAHEAD);
802 atomic_clear_int(&fp->f_flag, FRDAHEAD);
810 * Check if the vnode is part of a union stack (either the
811 * "union" flag from mount(2) or unionfs).
813 * Prior to introduction of this op libc's readdir would call
814 * fstatfs(2), in effect unnecessarily copying kilobytes of
815 * data just to check fs name and a mount flag.
817 * Fixing the code to handle everything in the kernel instead
818 * is a non-trivial endeavor and has low priority, thus this
819 * horrible kludge facilitates the current behavior in a much
820 * cheaper manner until someone(tm) sorts this out.
822 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
825 if (fp->f_type != DTYPE_VNODE) {
832 * Since we don't prevent dooming the vnode even non-null mp
833 * found can become immediately stale. This is tolerable since
834 * mount points are type-stable (providing safe memory access)
835 * and any vfs op on this vnode going forward will return an
836 * error (meaning return value in this case is meaningless).
838 mp = atomic_load_ptr(&vp->v_mount);
839 if (__predict_false(mp == NULL)) {
844 td->td_retval[0] = 0;
845 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
846 mp->mnt_flag & MNT_UNION)
847 td->td_retval[0] = 1;
859 getmaxfd(struct thread *td)
862 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
866 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
869 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
871 struct filedesc *fdp;
872 struct filedescent *oldfde, *newfde;
875 u_long *oioctls, *nioctls;
882 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
883 MPASS(mode < FDDUP_LASTMODE);
886 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
889 * Verify we have a valid descriptor to dup from and possibly to
890 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
891 * return EINVAL when the new descriptor is out of bounds.
896 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
897 maxfd = getmaxfd(td);
899 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
903 if (fget_locked(fdp, old) == NULL)
905 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
906 td->td_retval[0] = new;
907 if (flags & FDDUP_FLAG_CLOEXEC)
908 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
913 oldfde = &fdp->fd_ofiles[old];
914 if (!fhold(oldfde->fde_file))
918 * If the caller specified a file descriptor, make sure the file
919 * table is large enough to hold it, and grab it. Otherwise, just
920 * allocate a new descriptor the usual way.
925 if ((error = fdalloc(td, new, &new)) != 0) {
926 fdrop(oldfde->fde_file, td);
930 case FDDUP_MUSTREPLACE:
931 /* Target file descriptor must exist. */
932 if (fget_locked(fdp, new) == NULL) {
933 fdrop(oldfde->fde_file, td);
938 if (new >= fdp->fd_nfiles) {
940 * The resource limits are here instead of e.g.
941 * fdalloc(), because the file descriptor table may be
942 * shared between processes, so we can't really use
943 * racct_add()/racct_sub(). Instead of counting the
944 * number of actually allocated descriptors, just put
945 * the limit on the size of the file descriptor table.
948 if (RACCT_ENABLED()) {
949 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
952 fdrop(oldfde->fde_file, td);
957 fdgrowtable_exp(fdp, new + 1);
959 if (!fdisused(fdp, new))
963 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
966 KASSERT(old != new, ("new fd is same as old"));
968 newfde = &fdp->fd_ofiles[new];
969 delfp = newfde->fde_file;
971 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
974 * Duplicate the source descriptor.
977 seqc_write_begin(&newfde->fde_seqc);
979 oioctls = filecaps_free_prep(&newfde->fde_caps);
980 memcpy(newfde, oldfde, fde_change_size);
981 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
983 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
984 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
986 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
988 seqc_write_end(&newfde->fde_seqc);
990 td->td_retval[0] = new;
995 (void) closefp(fdp, new, delfp, td, 1);
996 FILEDESC_UNLOCK_ASSERT(fdp);
999 FILEDESC_XUNLOCK(fdp);
1002 filecaps_free_finish(oioctls);
1007 * If sigio is on the list associated with a process or process group,
1008 * disable signalling from the device, remove sigio from the list and
1012 funsetown(struct sigio **sigiop)
1014 struct sigio *sigio;
1016 if (*sigiop == NULL)
1020 if (sigio == NULL) {
1024 *(sigio->sio_myref) = NULL;
1025 if ((sigio)->sio_pgid < 0) {
1026 struct pgrp *pg = (sigio)->sio_pgrp;
1028 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1029 sigio, sio_pgsigio);
1032 struct proc *p = (sigio)->sio_proc;
1034 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1035 sigio, sio_pgsigio);
1039 crfree(sigio->sio_ucred);
1040 free(sigio, M_SIGIO);
1044 * Free a list of sigio structures.
1045 * We only need to lock the SIGIO_LOCK because we have made ourselves
1046 * inaccessible to callers of fsetown and therefore do not need to lock
1047 * the proc or pgrp struct for the list manipulation.
1050 funsetownlst(struct sigiolst *sigiolst)
1054 struct sigio *sigio;
1056 sigio = SLIST_FIRST(sigiolst);
1063 * Every entry of the list should belong
1064 * to a single proc or pgrp.
1066 if (sigio->sio_pgid < 0) {
1067 pg = sigio->sio_pgrp;
1068 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1069 } else /* if (sigio->sio_pgid > 0) */ {
1070 p = sigio->sio_proc;
1071 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1075 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1076 *(sigio->sio_myref) = NULL;
1078 KASSERT(sigio->sio_pgid < 0,
1079 ("Proc sigio in pgrp sigio list"));
1080 KASSERT(sigio->sio_pgrp == pg,
1081 ("Bogus pgrp in sigio list"));
1083 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1086 } else /* if (p != NULL) */ {
1087 KASSERT(sigio->sio_pgid > 0,
1088 ("Pgrp sigio in proc sigio list"));
1089 KASSERT(sigio->sio_proc == p,
1090 ("Bogus proc in sigio list"));
1092 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1097 crfree(sigio->sio_ucred);
1098 free(sigio, M_SIGIO);
1105 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1107 * After permission checking, add a sigio structure to the sigio list for
1108 * the process or process group.
1111 fsetown(pid_t pgid, struct sigio **sigiop)
1115 struct sigio *sigio;
1125 /* Allocate and fill in the new sigio out of locks. */
1126 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1127 sigio->sio_pgid = pgid;
1128 sigio->sio_ucred = crhold(curthread->td_ucred);
1129 sigio->sio_myref = sigiop;
1131 sx_slock(&proctree_lock);
1140 * Policy - Don't allow a process to FSETOWN a process
1141 * in another session.
1143 * Remove this test to allow maximum flexibility or
1144 * restrict FSETOWN to the current process or process
1145 * group for maximum safety.
1148 if (proc->p_session != curthread->td_proc->p_session) {
1154 } else /* if (pgid < 0) */ {
1155 pgrp = pgfind(-pgid);
1163 * Policy - Don't allow a process to FSETOWN a process
1164 * in another session.
1166 * Remove this test to allow maximum flexibility or
1167 * restrict FSETOWN to the current process or process
1168 * group for maximum safety.
1170 if (pgrp->pg_session != curthread->td_proc->p_session) {
1181 * Since funsetownlst() is called without the proctree
1182 * locked, we need to check for P_WEXIT.
1183 * XXX: is ESRCH correct?
1185 if ((proc->p_flag & P_WEXIT) != 0) {
1190 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1191 sigio->sio_proc = proc;
1195 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1196 sigio->sio_pgrp = pgrp;
1199 sx_sunlock(&proctree_lock);
1206 sx_sunlock(&proctree_lock);
1207 crfree(sigio->sio_ucred);
1208 free(sigio, M_SIGIO);
1213 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1216 fgetown(struct sigio **sigiop)
1221 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1227 * Function drops the filedesc lock on return.
1230 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1235 FILEDESC_XLOCK_ASSERT(fdp);
1238 if (td->td_proc->p_fdtol != NULL) {
1240 * Ask fdfree() to sleep to ensure that all relevant
1241 * process leaders can be traversed in closef().
1243 fdp->fd_holdleaderscount++;
1250 * We now hold the fp reference that used to be owned by the
1251 * descriptor array. We have to unlock the FILEDESC *AFTER*
1252 * knote_fdclose to prevent a race of the fd getting opened, a knote
1253 * added, and deleteing a knote for the new fd.
1255 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1256 knote_fdclose(td, fd);
1259 * We need to notify mqueue if the object is of type mqueue.
1261 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1262 mq_fdclose(td, fd, fp);
1263 FILEDESC_XUNLOCK(fdp);
1265 error = closef(fp, td);
1267 FILEDESC_XLOCK(fdp);
1268 fdp->fd_holdleaderscount--;
1269 if (fdp->fd_holdleaderscount == 0 &&
1270 fdp->fd_holdleaderswakeup != 0) {
1271 fdp->fd_holdleaderswakeup = 0;
1272 wakeup(&fdp->fd_holdleaderscount);
1274 FILEDESC_XUNLOCK(fdp);
1280 * Close a file descriptor.
1282 #ifndef _SYS_SYSPROTO_H_
1289 sys_close(struct thread *td, struct close_args *uap)
1292 return (kern_close(td, uap->fd));
1296 kern_close(struct thread *td, int fd)
1298 struct filedesc *fdp;
1301 fdp = td->td_proc->p_fd;
1303 AUDIT_SYSCLOSE(td, fd);
1305 FILEDESC_XLOCK(fdp);
1306 if ((fp = fget_locked(fdp, fd)) == NULL) {
1307 FILEDESC_XUNLOCK(fdp);
1312 /* closefp() drops the FILEDESC lock for us. */
1313 return (closefp(fdp, fd, fp, td, 1));
1317 kern_close_range(struct thread *td, u_int lowfd, u_int highfd)
1319 struct filedesc *fdp;
1323 fdp = td->td_proc->p_fd;
1324 FILEDESC_SLOCK(fdp);
1327 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1328 * open should not be a usage error. From a close_range() perspective,
1329 * close_range(3, ~0U, 0) in the same scenario should also likely not
1330 * be a usage error as all fd above 3 are in-fact already closed.
1332 if (highfd < lowfd) {
1336 /* Clamped to [lowfd, fd_lastfile] */
1337 highfd = MIN(highfd, fdp->fd_lastfile);
1338 for (fd = lowfd; fd <= highfd; fd++) {
1339 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1340 FILEDESC_SUNLOCK(fdp);
1341 (void)kern_close(td, fd);
1342 FILEDESC_SLOCK(fdp);
1346 FILEDESC_SUNLOCK(fdp);
1350 #ifndef _SYS_SYSPROTO_H_
1351 struct close_range_args {
1358 sys_close_range(struct thread *td, struct close_range_args *uap)
1361 /* No flags currently defined */
1362 if (uap->flags != 0)
1364 return (kern_close_range(td, uap->lowfd, uap->highfd));
1368 * Close open file descriptors.
1370 #ifndef _SYS_SYSPROTO_H_
1371 struct closefrom_args {
1377 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1381 AUDIT_ARG_FD(uap->lowfd);
1384 * Treat negative starting file descriptor values identical to
1385 * closefrom(0) which closes all files.
1387 lowfd = MAX(0, uap->lowfd);
1388 return (kern_close_range(td, lowfd, ~0U));
1391 #if defined(COMPAT_43)
1393 * Return status information about a file descriptor.
1395 #ifndef _SYS_SYSPROTO_H_
1396 struct ofstat_args {
1403 ofstat(struct thread *td, struct ofstat_args *uap)
1409 error = kern_fstat(td, uap->fd, &ub);
1412 error = copyout(&oub, uap->sb, sizeof(oub));
1416 #endif /* COMPAT_43 */
1418 #if defined(COMPAT_FREEBSD11)
1420 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1423 struct freebsd11_stat osb;
1426 error = kern_fstat(td, uap->fd, &sb);
1429 error = freebsd11_cvtstat(&sb, &osb);
1431 error = copyout(&osb, uap->sb, sizeof(osb));
1434 #endif /* COMPAT_FREEBSD11 */
1437 * Return status information about a file descriptor.
1439 #ifndef _SYS_SYSPROTO_H_
1447 sys_fstat(struct thread *td, struct fstat_args *uap)
1452 error = kern_fstat(td, uap->fd, &ub);
1454 error = copyout(&ub, uap->sb, sizeof(ub));
1459 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1466 error = fget(td, fd, &cap_fstat_rights, &fp);
1467 if (__predict_false(error != 0))
1470 AUDIT_ARG_FILE(td->td_proc, fp);
1472 error = fo_stat(fp, sbp, td->td_ucred, td);
1474 #ifdef __STAT_TIME_T_EXT
1475 sbp->st_atim_ext = 0;
1476 sbp->st_mtim_ext = 0;
1477 sbp->st_ctim_ext = 0;
1478 sbp->st_btim_ext = 0;
1481 if (KTRPOINT(td, KTR_STRUCT))
1482 ktrstat_error(sbp, error);
1487 #if defined(COMPAT_FREEBSD11)
1489 * Return status information about a file descriptor.
1491 #ifndef _SYS_SYSPROTO_H_
1492 struct freebsd11_nfstat_args {
1499 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1505 error = kern_fstat(td, uap->fd, &ub);
1507 freebsd11_cvtnstat(&ub, &nub);
1508 error = copyout(&nub, uap->sb, sizeof(nub));
1512 #endif /* COMPAT_FREEBSD11 */
1515 * Return pathconf information about a file descriptor.
1517 #ifndef _SYS_SYSPROTO_H_
1518 struct fpathconf_args {
1525 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1530 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1532 td->td_retval[0] = value;
1537 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1543 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1547 if (name == _PC_ASYNC_IO) {
1548 *valuep = _POSIX_ASYNCHRONOUS_IO;
1553 vn_lock(vp, LK_SHARED | LK_RETRY);
1554 error = VOP_PATHCONF(vp, name, valuep);
1556 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1557 if (name != _PC_PIPE_BUF) {
1572 * Copy filecaps structure allocating memory for ioctls array if needed.
1574 * The last parameter indicates whether the fdtable is locked. If it is not and
1575 * ioctls are encountered, copying fails and the caller must lock the table.
1577 * Note that if the table was not locked, the caller has to check the relevant
1578 * sequence counter to determine whether the operation was successful.
1581 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1585 if (src->fc_ioctls != NULL && !locked)
1587 memcpy(dst, src, sizeof(*src));
1588 if (src->fc_ioctls == NULL)
1591 KASSERT(src->fc_nioctls > 0,
1592 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1594 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1595 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1596 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1601 filecaps_copy_prep(const struct filecaps *src)
1606 if (__predict_true(src->fc_ioctls == NULL))
1609 KASSERT(src->fc_nioctls > 0,
1610 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1612 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1613 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1618 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1624 if (__predict_true(src->fc_ioctls == NULL)) {
1625 MPASS(ioctls == NULL);
1629 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1630 dst->fc_ioctls = ioctls;
1631 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1635 * Move filecaps structure to the new place and clear the old place.
1638 filecaps_move(struct filecaps *src, struct filecaps *dst)
1642 bzero(src, sizeof(*src));
1646 * Fill the given filecaps structure with full rights.
1649 filecaps_fill(struct filecaps *fcaps)
1652 CAP_ALL(&fcaps->fc_rights);
1653 fcaps->fc_ioctls = NULL;
1654 fcaps->fc_nioctls = -1;
1655 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1659 * Free memory allocated within filecaps structure.
1662 filecaps_free(struct filecaps *fcaps)
1665 free(fcaps->fc_ioctls, M_FILECAPS);
1666 bzero(fcaps, sizeof(*fcaps));
1670 filecaps_free_prep(struct filecaps *fcaps)
1674 ioctls = fcaps->fc_ioctls;
1675 bzero(fcaps, sizeof(*fcaps));
1680 filecaps_free_finish(u_long *ioctls)
1683 free(ioctls, M_FILECAPS);
1687 * Validate the given filecaps structure.
1690 filecaps_validate(const struct filecaps *fcaps, const char *func)
1693 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1694 ("%s: invalid rights", func));
1695 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1696 ("%s: invalid fcntls", func));
1697 KASSERT(fcaps->fc_fcntls == 0 ||
1698 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1699 ("%s: fcntls without CAP_FCNTL", func));
1700 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1701 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1702 ("%s: invalid ioctls", func));
1703 KASSERT(fcaps->fc_nioctls == 0 ||
1704 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1705 ("%s: ioctls without CAP_IOCTL", func));
1709 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1713 FILEDESC_XLOCK_ASSERT(fdp);
1715 nfd1 = fdp->fd_nfiles * 2;
1718 fdgrowtable(fdp, nfd1);
1722 * Grow the file table to accommodate (at least) nfd descriptors.
1725 fdgrowtable(struct filedesc *fdp, int nfd)
1727 struct filedesc0 *fdp0;
1728 struct freetable *ft;
1729 struct fdescenttbl *ntable;
1730 struct fdescenttbl *otable;
1731 int nnfiles, onfiles;
1732 NDSLOTTYPE *nmap, *omap;
1735 * If lastfile is -1 this struct filedesc was just allocated and we are
1736 * growing it to accommodate for the one we are going to copy from. There
1737 * is no need to have a lock on this one as it's not visible to anyone.
1739 if (fdp->fd_lastfile != -1)
1740 FILEDESC_XLOCK_ASSERT(fdp);
1742 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1744 /* save old values */
1745 onfiles = fdp->fd_nfiles;
1746 otable = fdp->fd_files;
1749 /* compute the size of the new table */
1750 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1751 if (nnfiles <= onfiles)
1752 /* the table is already large enough */
1756 * Allocate a new table. We need enough space for the number of
1757 * entries, file entries themselves and the struct freetable we will use
1758 * when we decommission the table and place it on the freelist.
1759 * We place the struct freetable in the middle so we don't have
1760 * to worry about padding.
1762 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1763 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1764 sizeof(struct freetable),
1765 M_FILEDESC, M_ZERO | M_WAITOK);
1766 /* copy the old data */
1767 ntable->fdt_nfiles = nnfiles;
1768 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1769 onfiles * sizeof(ntable->fdt_ofiles[0]));
1772 * Allocate a new map only if the old is not large enough. It will
1773 * grow at a slower rate than the table as it can map more
1774 * entries than the table can hold.
1776 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1777 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1779 /* copy over the old data and update the pointer */
1780 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1785 * Make sure that ntable is correctly initialized before we replace
1786 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1789 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1792 * Do not free the old file table, as some threads may still
1793 * reference entries within it. Instead, place it on a freelist
1794 * which will be processed when the struct filedesc is released.
1796 * Note that if onfiles == NDFILE, we're dealing with the original
1797 * static allocation contained within (struct filedesc0 *)fdp,
1798 * which must not be freed.
1800 if (onfiles > NDFILE) {
1801 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1802 fdp0 = (struct filedesc0 *)fdp;
1803 ft->ft_table = otable;
1804 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1807 * The map does not have the same possibility of threads still
1808 * holding references to it. So always free it as long as it
1809 * does not reference the original static allocation.
1811 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1812 free(omap, M_FILEDESC);
1816 * Allocate a file descriptor for the process.
1819 fdalloc(struct thread *td, int minfd, int *result)
1821 struct proc *p = td->td_proc;
1822 struct filedesc *fdp = p->p_fd;
1823 int fd, maxfd, allocfd;
1828 FILEDESC_XLOCK_ASSERT(fdp);
1830 if (fdp->fd_freefile > minfd)
1831 minfd = fdp->fd_freefile;
1833 maxfd = getmaxfd(td);
1836 * Search the bitmap for a free descriptor starting at minfd.
1837 * If none is found, grow the file table.
1839 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1842 if (fd >= fdp->fd_nfiles) {
1843 allocfd = min(fd * 2, maxfd);
1845 if (RACCT_ENABLED()) {
1846 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1852 * fd is already equal to first free descriptor >= minfd, so
1853 * we only need to grow the table and we are done.
1855 fdgrowtable_exp(fdp, allocfd);
1859 * Perform some sanity checks, then mark the file descriptor as
1860 * used and return it to the caller.
1862 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1863 ("invalid descriptor %d", fd));
1864 KASSERT(!fdisused(fdp, fd),
1865 ("fd_first_free() returned non-free descriptor"));
1866 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1867 ("file descriptor isn't free"));
1874 * Allocate n file descriptors for the process.
1877 fdallocn(struct thread *td, int minfd, int *fds, int n)
1879 struct proc *p = td->td_proc;
1880 struct filedesc *fdp = p->p_fd;
1883 FILEDESC_XLOCK_ASSERT(fdp);
1885 for (i = 0; i < n; i++)
1886 if (fdalloc(td, 0, &fds[i]) != 0)
1890 for (i--; i >= 0; i--)
1891 fdunused(fdp, fds[i]);
1899 * Create a new open file structure and allocate a file descriptor for the
1900 * process that refers to it. We add one reference to the file for the
1901 * descriptor table and one reference for resultfp. This is to prevent us
1902 * being preempted and the entry in the descriptor table closed after we
1903 * release the FILEDESC lock.
1906 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1907 struct filecaps *fcaps)
1912 error = falloc_noinstall(td, &fp);
1914 return (error); /* no reference held on error */
1916 error = finstall(td, fp, &fd, flags, fcaps);
1918 fdrop(fp, td); /* one reference (fp only) */
1922 if (resultfp != NULL)
1923 *resultfp = fp; /* copy out result */
1925 fdrop(fp, td); /* release local reference */
1927 if (resultfd != NULL)
1934 * Create a new open file structure without allocating a file descriptor.
1937 falloc_noinstall(struct thread *td, struct file **resultfp)
1940 int maxuserfiles = maxfiles - (maxfiles / 20);
1942 static struct timeval lastfail;
1945 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1947 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1948 if ((openfiles_new >= maxuserfiles &&
1949 priv_check(td, PRIV_MAXFILES) != 0) ||
1950 openfiles_new >= maxfiles) {
1951 atomic_subtract_int(&openfiles, 1);
1952 if (ppsratecheck(&lastfail, &curfail, 1)) {
1953 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1954 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1958 fp = uma_zalloc(file_zone, M_WAITOK);
1959 bzero(fp, sizeof(*fp));
1960 refcount_init(&fp->f_count, 1);
1961 fp->f_cred = crhold(td->td_ucred);
1962 fp->f_ops = &badfileops;
1968 * Install a file in a file descriptor table.
1971 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1972 struct filecaps *fcaps)
1974 struct filedescent *fde;
1978 filecaps_validate(fcaps, __func__);
1979 FILEDESC_XLOCK_ASSERT(fdp);
1981 fde = &fdp->fd_ofiles[fd];
1983 seqc_write_begin(&fde->fde_seqc);
1986 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1988 filecaps_move(fcaps, &fde->fde_caps);
1990 filecaps_fill(&fde->fde_caps);
1992 seqc_write_end(&fde->fde_seqc);
1997 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1998 struct filecaps *fcaps)
2000 struct filedesc *fdp = td->td_proc->p_fd;
2007 FILEDESC_XLOCK(fdp);
2008 error = fdalloc(td, 0, fd);
2009 if (__predict_false(error != 0)) {
2010 FILEDESC_XUNLOCK(fdp);
2014 _finstall(fdp, fp, *fd, flags, fcaps);
2015 FILEDESC_XUNLOCK(fdp);
2020 * Build a new filedesc structure from another.
2021 * Copy the current, root, and jail root vnode references.
2023 * If fdp is not NULL, return with it shared locked.
2026 fdinit(struct filedesc *fdp, bool prepfiles)
2028 struct filedesc0 *newfdp0;
2029 struct filedesc *newfdp;
2032 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2033 newfdp = &newfdp0->fd_fd;
2035 /* Create the file descriptor table. */
2036 FILEDESC_LOCK_INIT(newfdp);
2037 refcount_init(&newfdp->fd_refcnt, 1);
2038 refcount_init(&newfdp->fd_holdcnt, 1);
2039 newfdp->fd_cmask = CMASK;
2040 newfdp->fd_map = newfdp0->fd_dmap;
2041 newfdp->fd_lastfile = -1;
2042 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2043 newfdp->fd_files->fdt_nfiles = NDFILE;
2046 newpwd = pwd_alloc();
2047 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2051 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2052 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2054 FILEDESC_SLOCK(fdp);
2055 newpwd = pwd_hold_filedesc(fdp);
2056 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2059 FILEDESC_SUNLOCK(fdp);
2061 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2062 FILEDESC_SUNLOCK(fdp);
2063 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2064 FILEDESC_SLOCK(fdp);
2071 static struct filedesc *
2072 fdhold(struct proc *p)
2074 struct filedesc *fdp;
2076 PROC_LOCK_ASSERT(p, MA_OWNED);
2079 refcount_acquire(&fdp->fd_holdcnt);
2084 fddrop(struct filedesc *fdp)
2087 if (fdp->fd_holdcnt > 1) {
2088 if (refcount_release(&fdp->fd_holdcnt) == 0)
2092 FILEDESC_LOCK_DESTROY(fdp);
2093 uma_zfree(filedesc0_zone, fdp);
2097 * Share a filedesc structure.
2100 fdshare(struct filedesc *fdp)
2103 refcount_acquire(&fdp->fd_refcnt);
2108 * Unshare a filedesc structure, if necessary by making a copy
2111 fdunshare(struct thread *td)
2113 struct filedesc *tmp;
2114 struct proc *p = td->td_proc;
2116 if (p->p_fd->fd_refcnt == 1)
2119 tmp = fdcopy(p->p_fd);
2125 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2129 td->td_proc->p_fd = fdp;
2133 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2134 * this is to ease callers, not catch errors.
2137 fdcopy(struct filedesc *fdp)
2139 struct filedesc *newfdp;
2140 struct filedescent *nfde, *ofde;
2145 newfdp = fdinit(fdp, true);
2146 /* copy all passable descriptors (i.e. not kqueue) */
2147 newfdp->fd_freefile = -1;
2148 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2149 ofde = &fdp->fd_ofiles[i];
2150 if (ofde->fde_file == NULL ||
2151 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2152 !fhold(ofde->fde_file)) {
2153 if (newfdp->fd_freefile == -1)
2154 newfdp->fd_freefile = i;
2157 nfde = &newfdp->fd_ofiles[i];
2159 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2160 fdused_init(newfdp, i);
2161 newfdp->fd_lastfile = i;
2163 if (newfdp->fd_freefile == -1)
2164 newfdp->fd_freefile = i;
2165 newfdp->fd_cmask = fdp->fd_cmask;
2166 FILEDESC_SUNLOCK(fdp);
2171 * Copies a filedesc structure, while remapping all file descriptors
2172 * stored inside using a translation table.
2174 * File descriptors are copied over to the new file descriptor table,
2175 * regardless of whether the close-on-exec flag is set.
2178 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2179 struct filedesc **ret)
2181 struct filedesc *newfdp;
2182 struct filedescent *nfde, *ofde;
2187 newfdp = fdinit(fdp, true);
2188 if (nfds > fdp->fd_lastfile + 1) {
2189 /* New table cannot be larger than the old one. */
2193 /* Copy all passable descriptors (i.e. not kqueue). */
2194 newfdp->fd_freefile = nfds;
2195 for (i = 0; i < nfds; ++i) {
2196 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2197 /* File descriptor out of bounds. */
2201 ofde = &fdp->fd_ofiles[fds[i]];
2202 if (ofde->fde_file == NULL) {
2203 /* Unused file descriptor. */
2207 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2208 /* File descriptor cannot be passed. */
2212 if (!fhold(nfde->fde_file)) {
2216 nfde = &newfdp->fd_ofiles[i];
2218 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2219 fdused_init(newfdp, i);
2220 newfdp->fd_lastfile = i;
2222 newfdp->fd_cmask = fdp->fd_cmask;
2223 FILEDESC_SUNLOCK(fdp);
2227 FILEDESC_SUNLOCK(fdp);
2228 fdescfree_remapped(newfdp);
2233 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2234 * one of processes using it exits) and the table used to be shared.
2237 fdclearlocks(struct thread *td)
2239 struct filedesc *fdp;
2240 struct filedesc_to_leader *fdtol;
2250 MPASS(fdtol != NULL);
2252 FILEDESC_XLOCK(fdp);
2253 KASSERT(fdtol->fdl_refcount > 0,
2254 ("filedesc_to_refcount botch: fdl_refcount=%d",
2255 fdtol->fdl_refcount));
2256 if (fdtol->fdl_refcount == 1 &&
2257 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2258 for (i = 0; i <= fdp->fd_lastfile; i++) {
2259 fp = fdp->fd_ofiles[i].fde_file;
2260 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2263 FILEDESC_XUNLOCK(fdp);
2264 lf.l_whence = SEEK_SET;
2267 lf.l_type = F_UNLCK;
2269 (void) VOP_ADVLOCK(vp,
2270 (caddr_t)p->p_leader, F_UNLCK,
2272 FILEDESC_XLOCK(fdp);
2277 if (fdtol->fdl_refcount == 1) {
2278 if (fdp->fd_holdleaderscount > 0 &&
2279 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2281 * close() or kern_dup() has cleared a reference
2282 * in a shared file descriptor table.
2284 fdp->fd_holdleaderswakeup = 1;
2285 sx_sleep(&fdp->fd_holdleaderscount,
2286 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2289 if (fdtol->fdl_holdcount > 0) {
2291 * Ensure that fdtol->fdl_leader remains
2292 * valid in closef().
2294 fdtol->fdl_wakeup = 1;
2295 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2300 fdtol->fdl_refcount--;
2301 if (fdtol->fdl_refcount == 0 &&
2302 fdtol->fdl_holdcount == 0) {
2303 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2304 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2308 FILEDESC_XUNLOCK(fdp);
2310 free(fdtol, M_FILEDESC_TO_LEADER);
2314 * Release a filedesc structure.
2317 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2319 struct filedesc0 *fdp0;
2320 struct freetable *ft, *tft;
2321 struct filedescent *fde;
2325 for (i = 0; i <= fdp->fd_lastfile; i++) {
2326 fde = &fdp->fd_ofiles[i];
2331 (void) closef(fp, td);
2337 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2338 free(fdp->fd_map, M_FILEDESC);
2339 if (fdp->fd_nfiles > NDFILE)
2340 free(fdp->fd_files, M_FILEDESC);
2342 fdp0 = (struct filedesc0 *)fdp;
2343 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2344 free(ft->ft_table, M_FILEDESC);
2350 fdescfree(struct thread *td)
2353 struct filedesc *fdp;
2361 if (RACCT_ENABLED())
2362 racct_set_unlocked(p, RACCT_NOFILE, 0);
2365 if (p->p_fdtol != NULL)
2372 if (refcount_release(&fdp->fd_refcnt) == 0)
2375 FILEDESC_XLOCK(fdp);
2376 pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2378 FILEDESC_XUNLOCK(fdp);
2382 fdescfree_fds(td, fdp, 1);
2386 fdescfree_remapped(struct filedesc *fdp)
2389 pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2390 fdescfree_fds(curthread, fdp, 0);
2394 * For setugid programs, we don't want to people to use that setugidness
2395 * to generate error messages which write to a file which otherwise would
2396 * otherwise be off-limits to the process. We check for filesystems where
2397 * the vnode can change out from under us after execve (like [lin]procfs).
2399 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2400 * sufficient. We also don't check for setugidness since we know we are.
2403 is_unsafe(struct file *fp)
2407 if (fp->f_type != DTYPE_VNODE)
2411 return ((vp->v_vflag & VV_PROCDEP) != 0);
2415 * Make this setguid thing safe, if at all possible.
2418 fdsetugidsafety(struct thread *td)
2420 struct filedesc *fdp;
2424 fdp = td->td_proc->p_fd;
2425 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2426 MPASS(fdp->fd_nfiles >= 3);
2427 for (i = 0; i <= 2; i++) {
2428 fp = fdp->fd_ofiles[i].fde_file;
2429 if (fp != NULL && is_unsafe(fp)) {
2430 FILEDESC_XLOCK(fdp);
2431 knote_fdclose(td, i);
2433 * NULL-out descriptor prior to close to avoid
2434 * a race while close blocks.
2437 FILEDESC_XUNLOCK(fdp);
2438 (void) closef(fp, td);
2444 * If a specific file object occupies a specific file descriptor, close the
2445 * file descriptor entry and drop a reference on the file object. This is a
2446 * convenience function to handle a subsequent error in a function that calls
2447 * falloc() that handles the race that another thread might have closed the
2448 * file descriptor out from under the thread creating the file object.
2451 fdclose(struct thread *td, struct file *fp, int idx)
2453 struct filedesc *fdp = td->td_proc->p_fd;
2455 FILEDESC_XLOCK(fdp);
2456 if (fdp->fd_ofiles[idx].fde_file == fp) {
2458 FILEDESC_XUNLOCK(fdp);
2461 FILEDESC_XUNLOCK(fdp);
2465 * Close any files on exec?
2468 fdcloseexec(struct thread *td)
2470 struct filedesc *fdp;
2471 struct filedescent *fde;
2475 fdp = td->td_proc->p_fd;
2476 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2477 for (i = 0; i <= fdp->fd_lastfile; i++) {
2478 fde = &fdp->fd_ofiles[i];
2480 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2481 (fde->fde_flags & UF_EXCLOSE))) {
2482 FILEDESC_XLOCK(fdp);
2484 (void) closefp(fdp, i, fp, td, 0);
2485 FILEDESC_UNLOCK_ASSERT(fdp);
2491 * It is unsafe for set[ug]id processes to be started with file
2492 * descriptors 0..2 closed, as these descriptors are given implicit
2493 * significance in the Standard C library. fdcheckstd() will create a
2494 * descriptor referencing /dev/null for each of stdin, stdout, and
2495 * stderr that is not already open.
2498 fdcheckstd(struct thread *td)
2500 struct filedesc *fdp;
2502 int i, error, devnull;
2504 fdp = td->td_proc->p_fd;
2505 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2506 MPASS(fdp->fd_nfiles >= 3);
2508 for (i = 0; i <= 2; i++) {
2509 if (fdp->fd_ofiles[i].fde_file != NULL)
2512 save = td->td_retval[0];
2513 if (devnull != -1) {
2514 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2516 error = kern_openat(td, AT_FDCWD, "/dev/null",
2517 UIO_SYSSPACE, O_RDWR, 0);
2519 devnull = td->td_retval[0];
2520 KASSERT(devnull == i, ("we didn't get our fd"));
2523 td->td_retval[0] = save;
2531 * Internal form of close. Decrement reference count on file structure.
2532 * Note: td may be NULL when closing a file that was being passed in a
2536 closef(struct file *fp, struct thread *td)
2540 struct filedesc_to_leader *fdtol;
2541 struct filedesc *fdp;
2544 * POSIX record locking dictates that any close releases ALL
2545 * locks owned by this process. This is handled by setting
2546 * a flag in the unlock to free ONLY locks obeying POSIX
2547 * semantics, and not to free BSD-style file locks.
2548 * If the descriptor was in a message, POSIX-style locks
2549 * aren't passed with the descriptor, and the thread pointer
2550 * will be NULL. Callers should be careful only to pass a
2551 * NULL thread pointer when there really is no owning
2552 * context that might have locks, or the locks will be
2555 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2557 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2558 lf.l_whence = SEEK_SET;
2561 lf.l_type = F_UNLCK;
2562 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2563 F_UNLCK, &lf, F_POSIX);
2565 fdtol = td->td_proc->p_fdtol;
2566 if (fdtol != NULL) {
2568 * Handle special case where file descriptor table is
2569 * shared between multiple process leaders.
2571 fdp = td->td_proc->p_fd;
2572 FILEDESC_XLOCK(fdp);
2573 for (fdtol = fdtol->fdl_next;
2574 fdtol != td->td_proc->p_fdtol;
2575 fdtol = fdtol->fdl_next) {
2576 if ((fdtol->fdl_leader->p_flag &
2579 fdtol->fdl_holdcount++;
2580 FILEDESC_XUNLOCK(fdp);
2581 lf.l_whence = SEEK_SET;
2584 lf.l_type = F_UNLCK;
2586 (void) VOP_ADVLOCK(vp,
2587 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2589 FILEDESC_XLOCK(fdp);
2590 fdtol->fdl_holdcount--;
2591 if (fdtol->fdl_holdcount == 0 &&
2592 fdtol->fdl_wakeup != 0) {
2593 fdtol->fdl_wakeup = 0;
2597 FILEDESC_XUNLOCK(fdp);
2600 return (fdrop(fp, td));
2604 * Initialize the file pointer with the specified properties.
2606 * The ops are set with release semantics to be certain that the flags, type,
2607 * and data are visible when ops is. This is to prevent ops methods from being
2608 * called with bad data.
2611 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2616 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2620 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2621 struct file **fpp, struct filecaps *havecapsp)
2623 struct filedescent *fde;
2626 FILEDESC_LOCK_ASSERT(fdp);
2628 fde = fdeget_locked(fdp, fd);
2635 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2640 if (havecapsp != NULL)
2641 filecaps_copy(&fde->fde_caps, havecapsp, true);
2643 *fpp = fde->fde_file;
2651 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2652 struct file **fpp, struct filecaps *havecapsp)
2654 struct filedesc *fdp = td->td_proc->p_fd;
2656 #ifndef CAPABILITIES
2657 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2658 if (havecapsp != NULL && error == 0)
2659 filecaps_fill(havecapsp);
2666 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2670 if (havecapsp != NULL) {
2671 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2672 havecapsp, false)) {
2678 if (!fd_modified(fdp, fd, seq))
2687 FILEDESC_SLOCK(fdp);
2688 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2689 if (error == 0 && !fhold(*fpp))
2691 FILEDESC_SUNLOCK(fdp);
2697 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2698 struct file **fpp, seqc_t *seqp)
2701 const struct filedescent *fde;
2703 const struct fdescenttbl *fdt;
2707 cap_rights_t haverights;
2711 fdt = fdp->fd_files;
2712 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2715 * Fetch the descriptor locklessly. We avoid fdrop() races by
2716 * never raising a refcount above 0. To accomplish this we have
2717 * to use a cmpset loop rather than an atomic_add. The descriptor
2718 * must be re-verified once we acquire a reference to be certain
2719 * that the identity is still correct and we did not lose a race
2720 * due to preemption.
2724 seq = seqc_read(fd_seqc(fdt, fd));
2725 fde = &fdt->fdt_ofiles[fd];
2726 haverights = *cap_rights_fde_inline(fde);
2728 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2731 fp = fdt->fdt_ofiles[fd].fde_file;
2736 error = cap_check_inline(&haverights, needrightsp);
2740 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2742 * The count was found either saturated or zero.
2743 * This re-read is not any more racy than using the
2744 * return value from fcmpset.
2746 if (fp->f_count != 0)
2749 * Force a reload. Other thread could reallocate the
2750 * table before this fd was closed, so it is possible
2751 * that there is a stale fp pointer in cached version.
2753 fdt = atomic_load_ptr(&fdp->fd_files);
2757 * Use an acquire barrier to force re-reading of fdt so it is
2758 * refreshed for verification.
2760 atomic_thread_fence_acq();
2761 fdt = fdp->fd_files;
2763 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2765 if (fp == fdt->fdt_ofiles[fd].fde_file)
2768 fdrop(fp, curthread);
2780 * See the comments in fget_unlocked_seq for an explanation of how this works.
2782 * This is a simplified variant which bails out to the aforementioned routine
2783 * if anything goes wrong. In practice this only happens when userspace is
2784 * racing with itself.
2787 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2791 const struct filedescent *fde;
2793 const struct fdescenttbl *fdt;
2797 const cap_rights_t *haverights;
2800 fdt = fdp->fd_files;
2801 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2804 seq = seqc_read_any(fd_seqc(fdt, fd));
2805 if (__predict_false(seqc_in_modify(seq)))
2807 fde = &fdt->fdt_ofiles[fd];
2808 haverights = cap_rights_fde_inline(fde);
2811 fp = fdt->fdt_ofiles[fd].fde_file;
2813 if (__predict_false(fp == NULL))
2816 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2819 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2823 * Use an acquire barrier to force re-reading of fdt so it is
2824 * refreshed for verification.
2826 atomic_thread_fence_acq();
2827 fdt = fdp->fd_files;
2829 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2831 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2837 fdrop(fp, curthread);
2839 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2843 * Extract the file pointer associated with the specified descriptor for the
2844 * current user process.
2846 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2849 * File's rights will be checked against the capability rights mask.
2851 * If an error occurred the non-zero error is returned and *fpp is set to
2852 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2853 * responsible for fdrop().
2856 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2857 cap_rights_t *needrightsp)
2859 struct filedesc *fdp;
2864 fdp = td->td_proc->p_fd;
2865 error = fget_unlocked(fdp, fd, needrightsp, &fp);
2866 if (__predict_false(error != 0))
2868 if (__predict_false(fp->f_ops == &badfileops)) {
2874 * FREAD and FWRITE failure return EBADF as per POSIX.
2880 if ((fp->f_flag & flags) == 0)
2884 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2885 ((fp->f_flag & FWRITE) != 0))
2891 KASSERT(0, ("wrong flags"));
2904 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2907 return (_fget(td, fd, fpp, 0, rightsp));
2911 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2915 #ifndef CAPABILITIES
2916 error = _fget(td, fd, fpp, 0, rightsp);
2917 if (maxprotp != NULL)
2918 *maxprotp = VM_PROT_ALL;
2921 cap_rights_t fdrights;
2922 struct filedesc *fdp;
2927 fdp = td->td_proc->p_fd;
2928 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2930 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2931 if (__predict_false(error != 0))
2933 if (__predict_false(fp->f_ops == &badfileops)) {
2937 if (maxprotp != NULL)
2938 fdrights = *cap_rights(fdp, fd);
2939 if (!fd_modified(fdp, fd, seq))
2945 * If requested, convert capability rights to access flags.
2947 if (maxprotp != NULL)
2948 *maxprotp = cap_rights_to_vmprot(&fdrights);
2955 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2958 return (_fget(td, fd, fpp, FREAD, rightsp));
2962 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2965 return (_fget(td, fd, fpp, FWRITE, rightsp));
2969 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2972 struct filedesc *fdp = td->td_proc->p_fd;
2973 #ifndef CAPABILITIES
2974 return (fget_unlocked(fdp, fd, rightsp, fpp));
2981 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2983 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2986 error = cap_fcntl_check(fdp, fd, needfcntl);
2987 if (!fd_modified(fdp, fd, seq))
3001 * Like fget() but loads the underlying vnode, or returns an error if the
3002 * descriptor does not represent a vnode. Note that pipes use vnodes but
3003 * never have VM objects. The returned vnode will be vref()'d.
3005 * XXX: what about the unused flags ?
3008 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3015 error = _fget(td, fd, &fp, flags, needrightsp);
3018 if (fp->f_vnode == NULL) {
3030 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3033 return (_fgetvp(td, fd, 0, rightsp, vpp));
3037 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3038 struct filecaps *havecaps, struct vnode **vpp)
3040 struct filecaps caps;
3044 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3047 if (fp->f_ops == &badfileops) {
3051 if (fp->f_vnode == NULL) {
3063 filecaps_free(&caps);
3069 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3072 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3076 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3079 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3084 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3088 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3093 * Handle the last reference to a file being closed.
3095 * Without the noinline attribute clang keeps inlining the func thorough this
3096 * file when fdrop is used.
3099 _fdrop(struct file *fp, struct thread *td)
3103 if (fp->f_count != 0)
3104 panic("fdrop: count %d", fp->f_count);
3105 error = fo_close(fp, td);
3106 atomic_subtract_int(&openfiles, 1);
3108 free(fp->f_advice, M_FADVISE);
3109 uma_zfree(file_zone, fp);
3115 * Apply an advisory lock on a file descriptor.
3117 * Just attempt to get a record lock of the requested type on the entire file
3118 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3120 #ifndef _SYS_SYSPROTO_H_
3128 sys_flock(struct thread *td, struct flock_args *uap)
3135 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3138 if (fp->f_type != DTYPE_VNODE) {
3140 return (EOPNOTSUPP);
3144 lf.l_whence = SEEK_SET;
3147 if (uap->how & LOCK_UN) {
3148 lf.l_type = F_UNLCK;
3149 atomic_clear_int(&fp->f_flag, FHASLOCK);
3150 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3153 if (uap->how & LOCK_EX)
3154 lf.l_type = F_WRLCK;
3155 else if (uap->how & LOCK_SH)
3156 lf.l_type = F_RDLCK;
3161 atomic_set_int(&fp->f_flag, FHASLOCK);
3162 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3163 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3169 * Duplicate the specified descriptor to a free descriptor.
3172 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3173 int openerror, int *indxp)
3175 struct filedescent *newfde, *oldfde;
3180 KASSERT(openerror == ENODEV || openerror == ENXIO,
3181 ("unexpected error %d in %s", openerror, __func__));
3184 * If the to-be-dup'd fd number is greater than the allowed number
3185 * of file descriptors, or the fd to be dup'd has already been
3186 * closed, then reject.
3188 FILEDESC_XLOCK(fdp);
3189 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3190 FILEDESC_XUNLOCK(fdp);
3194 error = fdalloc(td, 0, &indx);
3196 FILEDESC_XUNLOCK(fdp);
3201 * There are two cases of interest here.
3203 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3205 * For ENXIO steal away the file structure from (dfd) and store it in
3206 * (indx). (dfd) is effectively closed by this operation.
3208 switch (openerror) {
3211 * Check that the mode the file is being opened for is a
3212 * subset of the mode of the existing descriptor.
3214 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3215 fdunused(fdp, indx);
3216 FILEDESC_XUNLOCK(fdp);
3220 fdunused(fdp, indx);
3221 FILEDESC_XUNLOCK(fdp);
3224 newfde = &fdp->fd_ofiles[indx];
3225 oldfde = &fdp->fd_ofiles[dfd];
3226 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3228 seqc_write_begin(&newfde->fde_seqc);
3230 memcpy(newfde, oldfde, fde_change_size);
3231 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3234 seqc_write_end(&newfde->fde_seqc);
3239 * Steal away the file pointer from dfd and stuff it into indx.
3241 newfde = &fdp->fd_ofiles[indx];
3242 oldfde = &fdp->fd_ofiles[dfd];
3244 seqc_write_begin(&newfde->fde_seqc);
3246 memcpy(newfde, oldfde, fde_change_size);
3247 oldfde->fde_file = NULL;
3250 seqc_write_end(&newfde->fde_seqc);
3254 FILEDESC_XUNLOCK(fdp);
3260 * This sysctl determines if we will allow a process to chroot(2) if it
3261 * has a directory open:
3262 * 0: disallowed for all processes.
3263 * 1: allowed for processes that were not already chroot(2)'ed.
3264 * 2: allowed for all processes.
3267 static int chroot_allow_open_directories = 1;
3269 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3270 &chroot_allow_open_directories, 0,
3271 "Allow a process to chroot(2) if it has a directory open");
3274 * Helper function for raised chroot(2) security function: Refuse if
3275 * any filedescriptors are open directories.
3278 chroot_refuse_vdir_fds(struct filedesc *fdp)
3284 FILEDESC_LOCK_ASSERT(fdp);
3286 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3287 fp = fget_locked(fdp, fd);
3290 if (fp->f_type == DTYPE_VNODE) {
3292 if (vp->v_type == VDIR)
3300 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3303 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3304 vrefact(oldpwd->pwd_cdir);
3305 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3308 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3309 vrefact(oldpwd->pwd_rdir);
3310 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3313 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3314 vrefact(oldpwd->pwd_jdir);
3315 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3320 pwd_hold_filedesc(struct filedesc *fdp)
3324 FILEDESC_LOCK_ASSERT(fdp);
3325 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3327 refcount_acquire(&pwd->pwd_refcount);
3332 pwd_hold(struct thread *td)
3334 struct filedesc *fdp;
3337 fdp = td->td_proc->p_fd;
3341 pwd = smr_entered_load(&fdp->fd_pwd, pwd_smr);
3343 if (refcount_acquire_if_not_zero(&pwd->pwd_refcount))
3355 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3356 bzero(pwd, sizeof(*pwd));
3357 refcount_init(&pwd->pwd_refcount, 1);
3362 pwd_drop(struct pwd *pwd)
3365 if (!refcount_release(&pwd->pwd_refcount))
3368 if (pwd->pwd_cdir != NULL)
3369 vrele(pwd->pwd_cdir);
3370 if (pwd->pwd_rdir != NULL)
3371 vrele(pwd->pwd_rdir);
3372 if (pwd->pwd_jdir != NULL)
3373 vrele(pwd->pwd_jdir);
3374 uma_zfree_smr(pwd_zone, pwd);
3378 * Common routine for kern_chroot() and jail_attach(). The caller is
3379 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3380 * authorize this operation.
3383 pwd_chroot(struct thread *td, struct vnode *vp)
3385 struct filedesc *fdp;
3386 struct pwd *newpwd, *oldpwd;
3389 fdp = td->td_proc->p_fd;
3390 newpwd = pwd_alloc();
3391 FILEDESC_XLOCK(fdp);
3392 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3393 if (chroot_allow_open_directories == 0 ||
3394 (chroot_allow_open_directories == 1 &&
3395 oldpwd->pwd_rdir != rootvnode)) {
3396 error = chroot_refuse_vdir_fds(fdp);
3398 FILEDESC_XUNLOCK(fdp);
3405 newpwd->pwd_rdir = vp;
3406 if (oldpwd->pwd_jdir == NULL) {
3408 newpwd->pwd_jdir = vp;
3410 pwd_fill(oldpwd, newpwd);
3411 pwd_set(fdp, newpwd);
3412 FILEDESC_XUNLOCK(fdp);
3418 pwd_chdir(struct thread *td, struct vnode *vp)
3420 struct filedesc *fdp;
3421 struct pwd *newpwd, *oldpwd;
3423 VNPASS(vp->v_usecount > 0, vp);
3425 newpwd = pwd_alloc();
3426 fdp = td->td_proc->p_fd;
3427 FILEDESC_XLOCK(fdp);
3428 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3429 newpwd->pwd_cdir = vp;
3430 pwd_fill(oldpwd, newpwd);
3431 pwd_set(fdp, newpwd);
3432 FILEDESC_XUNLOCK(fdp);
3437 pwd_ensure_dirs(void)
3439 struct filedesc *fdp;
3440 struct pwd *oldpwd, *newpwd;
3442 fdp = curproc->p_fd;
3443 FILEDESC_XLOCK(fdp);
3444 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3445 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3446 FILEDESC_XUNLOCK(fdp);
3449 FILEDESC_XUNLOCK(fdp);
3451 newpwd = pwd_alloc();
3452 FILEDESC_XLOCK(fdp);
3453 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3454 pwd_fill(oldpwd, newpwd);
3455 if (newpwd->pwd_cdir == NULL) {
3457 newpwd->pwd_cdir = rootvnode;
3459 if (newpwd->pwd_rdir == NULL) {
3461 newpwd->pwd_rdir = rootvnode;
3463 pwd_set(fdp, newpwd);
3464 FILEDESC_XUNLOCK(fdp);
3469 * Scan all active processes and prisons to see if any of them have a current
3470 * or root directory of `olddp'. If so, replace them with the new mount point.
3473 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3475 struct filedesc *fdp;
3476 struct pwd *newpwd, *oldpwd;
3481 if (vrefcnt(olddp) == 1)
3484 newpwd = pwd_alloc();
3485 sx_slock(&allproc_lock);
3486 FOREACH_PROC_IN_SYSTEM(p) {
3492 FILEDESC_XLOCK(fdp);
3493 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3494 if (oldpwd == NULL ||
3495 (oldpwd->pwd_cdir != olddp &&
3496 oldpwd->pwd_rdir != olddp &&
3497 oldpwd->pwd_jdir != olddp)) {
3498 FILEDESC_XUNLOCK(fdp);
3502 if (oldpwd->pwd_cdir == olddp) {
3504 newpwd->pwd_cdir = newdp;
3506 if (oldpwd->pwd_rdir == olddp) {
3508 newpwd->pwd_rdir = newdp;
3510 if (oldpwd->pwd_jdir == olddp) {
3512 newpwd->pwd_jdir = newdp;
3514 pwd_fill(oldpwd, newpwd);
3515 pwd_set(fdp, newpwd);
3516 FILEDESC_XUNLOCK(fdp);
3519 newpwd = pwd_alloc();
3521 sx_sunlock(&allproc_lock);
3523 if (rootvnode == olddp) {
3528 mtx_lock(&prison0.pr_mtx);
3529 if (prison0.pr_root == olddp) {
3531 prison0.pr_root = newdp;
3534 mtx_unlock(&prison0.pr_mtx);
3535 sx_slock(&allprison_lock);
3536 TAILQ_FOREACH(pr, &allprison, pr_list) {
3537 mtx_lock(&pr->pr_mtx);
3538 if (pr->pr_root == olddp) {
3540 pr->pr_root = newdp;
3543 mtx_unlock(&pr->pr_mtx);
3545 sx_sunlock(&allprison_lock);
3550 struct filedesc_to_leader *
3551 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3553 struct filedesc_to_leader *fdtol;
3555 fdtol = malloc(sizeof(struct filedesc_to_leader),
3556 M_FILEDESC_TO_LEADER, M_WAITOK);
3557 fdtol->fdl_refcount = 1;
3558 fdtol->fdl_holdcount = 0;
3559 fdtol->fdl_wakeup = 0;
3560 fdtol->fdl_leader = leader;
3562 FILEDESC_XLOCK(fdp);
3563 fdtol->fdl_next = old->fdl_next;
3564 fdtol->fdl_prev = old;
3565 old->fdl_next = fdtol;
3566 fdtol->fdl_next->fdl_prev = fdtol;
3567 FILEDESC_XUNLOCK(fdp);
3569 fdtol->fdl_next = fdtol;
3570 fdtol->fdl_prev = fdtol;
3576 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3578 struct filedesc *fdp;
3579 int i, count, slots;
3581 if (*(int *)arg1 != 0)
3584 fdp = curproc->p_fd;
3586 FILEDESC_SLOCK(fdp);
3587 slots = NDSLOTS(fdp->fd_lastfile + 1);
3588 for (i = 0; i < slots; i++)
3589 count += bitcountl(fdp->fd_map[i]);
3590 FILEDESC_SUNLOCK(fdp);
3592 return (SYSCTL_OUT(req, &count, sizeof(count)));
3595 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3596 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3597 "Number of open file descriptors");
3600 * Get file structures globally.
3603 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3606 struct filedesc *fdp;
3611 error = sysctl_wire_old_buffer(req, 0);
3614 if (req->oldptr == NULL) {
3616 sx_slock(&allproc_lock);
3617 FOREACH_PROC_IN_SYSTEM(p) {
3619 if (p->p_state == PRS_NEW) {
3627 /* overestimates sparse tables. */
3628 if (fdp->fd_lastfile > 0)
3629 n += fdp->fd_lastfile;
3632 sx_sunlock(&allproc_lock);
3633 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3636 bzero(&xf, sizeof(xf));
3637 xf.xf_size = sizeof(xf);
3638 sx_slock(&allproc_lock);
3639 FOREACH_PROC_IN_SYSTEM(p) {
3641 if (p->p_state == PRS_NEW) {
3645 if (p_cansee(req->td, p) != 0) {
3649 xf.xf_pid = p->p_pid;
3650 xf.xf_uid = p->p_ucred->cr_uid;
3655 FILEDESC_SLOCK(fdp);
3656 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3657 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3660 xf.xf_file = (uintptr_t)fp;
3661 xf.xf_data = (uintptr_t)fp->f_data;
3662 xf.xf_vnode = (uintptr_t)fp->f_vnode;
3663 xf.xf_type = (uintptr_t)fp->f_type;
3664 xf.xf_count = fp->f_count;
3666 xf.xf_offset = foffset_get(fp);
3667 xf.xf_flag = fp->f_flag;
3668 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3672 FILEDESC_SUNLOCK(fdp);
3677 sx_sunlock(&allproc_lock);
3681 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3682 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3684 #ifdef KINFO_FILE_SIZE
3685 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3689 xlate_fflags(int fflags)
3691 static const struct {
3694 } fflags_table[] = {
3695 { FAPPEND, KF_FLAG_APPEND },
3696 { FASYNC, KF_FLAG_ASYNC },
3697 { FFSYNC, KF_FLAG_FSYNC },
3698 { FHASLOCK, KF_FLAG_HASLOCK },
3699 { FNONBLOCK, KF_FLAG_NONBLOCK },
3700 { FREAD, KF_FLAG_READ },
3701 { FWRITE, KF_FLAG_WRITE },
3702 { O_CREAT, KF_FLAG_CREAT },
3703 { O_DIRECT, KF_FLAG_DIRECT },
3704 { O_EXCL, KF_FLAG_EXCL },
3705 { O_EXEC, KF_FLAG_EXEC },
3706 { O_EXLOCK, KF_FLAG_EXLOCK },
3707 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3708 { O_SHLOCK, KF_FLAG_SHLOCK },
3709 { O_TRUNC, KF_FLAG_TRUNC }
3715 for (i = 0; i < nitems(fflags_table); i++)
3716 if (fflags & fflags_table[i].fflag)
3717 kflags |= fflags_table[i].kf_fflag;
3721 /* Trim unused data from kf_path by truncating the structure size. */
3723 pack_kinfo(struct kinfo_file *kif)
3726 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3727 strlen(kif->kf_path) + 1;
3728 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3732 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3733 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3737 bzero(kif, sizeof(*kif));
3739 /* Set a default type to allow for empty fill_kinfo() methods. */
3740 kif->kf_type = KF_TYPE_UNKNOWN;
3741 kif->kf_flags = xlate_fflags(fp->f_flag);
3742 if (rightsp != NULL)
3743 kif->kf_cap_rights = *rightsp;
3745 cap_rights_init_zero(&kif->kf_cap_rights);
3747 kif->kf_ref_count = fp->f_count;
3748 kif->kf_offset = foffset_get(fp);
3751 * This may drop the filedesc lock, so the 'fp' cannot be
3752 * accessed after this call.
3754 error = fo_fill_kinfo(fp, kif, fdp);
3756 kif->kf_status |= KF_ATTR_VALID;
3757 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3760 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3764 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3765 struct kinfo_file *kif, int flags)
3769 bzero(kif, sizeof(*kif));
3771 kif->kf_type = KF_TYPE_VNODE;
3772 error = vn_fill_kinfo_vnode(vp, kif);
3774 kif->kf_status |= KF_ATTR_VALID;
3775 kif->kf_flags = xlate_fflags(fflags);
3776 cap_rights_init_zero(&kif->kf_cap_rights);
3778 kif->kf_ref_count = -1;
3779 kif->kf_offset = -1;
3780 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3783 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3787 struct export_fd_buf {
3788 struct filedesc *fdp;
3791 struct kinfo_file kif;
3796 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3798 struct kinfo_file *kif;
3801 if (efbuf->remainder != -1) {
3802 if (efbuf->remainder < kif->kf_structsize) {
3803 /* Terminate export. */
3804 efbuf->remainder = 0;
3807 efbuf->remainder -= kif->kf_structsize;
3809 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3813 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3814 struct export_fd_buf *efbuf)
3818 if (efbuf->remainder == 0)
3820 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3822 FILEDESC_SUNLOCK(efbuf->fdp);
3823 error = export_kinfo_to_sb(efbuf);
3824 FILEDESC_SLOCK(efbuf->fdp);
3829 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3830 struct export_fd_buf *efbuf)
3834 if (efbuf->remainder == 0)
3836 if (efbuf->fdp != NULL)
3837 FILEDESC_SUNLOCK(efbuf->fdp);
3838 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3839 error = export_kinfo_to_sb(efbuf);
3840 if (efbuf->fdp != NULL)
3841 FILEDESC_SLOCK(efbuf->fdp);
3846 * Store a process file descriptor information to sbuf.
3848 * Takes a locked proc as argument, and returns with the proc unlocked.
3851 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3855 struct filedesc *fdp;
3856 struct export_fd_buf *efbuf;
3857 struct vnode *cttyvp, *textvp, *tracevp;
3860 cap_rights_t rights;
3862 PROC_LOCK_ASSERT(p, MA_OWNED);
3865 tracevp = p->p_tracevp;
3866 if (tracevp != NULL)
3869 textvp = p->p_textvp;
3872 /* Controlling tty. */
3874 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3875 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3881 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3884 efbuf->remainder = maxlen;
3885 efbuf->flags = flags;
3886 if (tracevp != NULL)
3887 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3890 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3892 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3898 FILEDESC_SLOCK(fdp);
3899 pwd = pwd_hold_filedesc(fdp);
3901 /* working directory */
3902 if (pwd->pwd_cdir != NULL) {
3903 vrefact(pwd->pwd_cdir);
3904 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3906 /* root directory */
3907 if (pwd->pwd_rdir != NULL) {
3908 vrefact(pwd->pwd_rdir);
3909 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3911 /* jail directory */
3912 if (pwd->pwd_jdir != NULL) {
3913 vrefact(pwd->pwd_jdir);
3914 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3918 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3919 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3922 rights = *cap_rights(fdp, i);
3923 #else /* !CAPABILITIES */
3924 rights = cap_no_rights;
3927 * Create sysctl entry. It is OK to drop the filedesc
3928 * lock inside of export_file_to_sb() as we will
3929 * re-validate and re-evaluate its properties when the
3932 error = export_file_to_sb(fp, i, &rights, efbuf);
3933 if (error != 0 || efbuf->remainder == 0)
3936 FILEDESC_SUNLOCK(fdp);
3939 free(efbuf, M_TEMP);
3943 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3946 * Get per-process file descriptors for use by procstat(1), et al.
3949 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3954 int error, error2, *name;
3958 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3959 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3960 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3965 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3966 error = kern_proc_filedesc_out(p, &sb, maxlen,
3967 KERN_FILEDESC_PACK_KINFO);
3968 error2 = sbuf_finish(&sb);
3970 return (error != 0 ? error : error2);
3973 #ifdef COMPAT_FREEBSD7
3974 #ifdef KINFO_OFILE_SIZE
3975 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3979 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3982 okif->kf_structsize = sizeof(*okif);
3983 okif->kf_type = kif->kf_type;
3984 okif->kf_fd = kif->kf_fd;
3985 okif->kf_ref_count = kif->kf_ref_count;
3986 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3987 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3988 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3989 okif->kf_offset = kif->kf_offset;
3990 if (kif->kf_type == KF_TYPE_VNODE)
3991 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
3993 okif->kf_vnode_type = KF_VTYPE_VNON;
3994 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3995 if (kif->kf_type == KF_TYPE_SOCKET) {
3996 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
3997 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
3998 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
3999 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4000 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4002 okif->kf_sa_local.ss_family = AF_UNSPEC;
4003 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4008 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4009 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
4014 FILEDESC_SUNLOCK(fdp);
4015 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4016 kinfo_to_okinfo(kif, okif);
4017 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4018 FILEDESC_SLOCK(fdp);
4023 * Get per-process file descriptors for use by procstat(1), et al.
4026 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4028 struct kinfo_ofile *okif;
4029 struct kinfo_file *kif;
4030 struct filedesc *fdp;
4032 int error, i, *name;
4037 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4044 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4045 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4046 FILEDESC_SLOCK(fdp);
4047 pwd = pwd_hold_filedesc(fdp);
4049 if (pwd->pwd_cdir != NULL)
4050 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4052 if (pwd->pwd_rdir != NULL)
4053 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4055 if (pwd->pwd_jdir != NULL)
4056 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4060 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4061 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4063 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4064 KERN_FILEDESC_PACK_KINFO);
4065 FILEDESC_SUNLOCK(fdp);
4066 kinfo_to_okinfo(kif, okif);
4067 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4068 FILEDESC_SLOCK(fdp);
4072 FILEDESC_SUNLOCK(fdp);
4079 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4080 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4081 "Process ofiledesc entries");
4082 #endif /* COMPAT_FREEBSD7 */
4085 vntype_to_kinfo(int vtype)
4090 } vtypes_table[] = {
4091 { VBAD, KF_VTYPE_VBAD },
4092 { VBLK, KF_VTYPE_VBLK },
4093 { VCHR, KF_VTYPE_VCHR },
4094 { VDIR, KF_VTYPE_VDIR },
4095 { VFIFO, KF_VTYPE_VFIFO },
4096 { VLNK, KF_VTYPE_VLNK },
4097 { VNON, KF_VTYPE_VNON },
4098 { VREG, KF_VTYPE_VREG },
4099 { VSOCK, KF_VTYPE_VSOCK }
4104 * Perform vtype translation.
4106 for (i = 0; i < nitems(vtypes_table); i++)
4107 if (vtypes_table[i].vtype == vtype)
4108 return (vtypes_table[i].kf_vtype);
4110 return (KF_VTYPE_UNKNOWN);
4113 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4114 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4115 "Process filedesc entries");
4118 * Store a process current working directory information to sbuf.
4120 * Takes a locked proc as argument, and returns with the proc unlocked.
4123 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4125 struct filedesc *fdp;
4127 struct export_fd_buf *efbuf;
4131 PROC_LOCK_ASSERT(p, MA_OWNED);
4138 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4141 efbuf->remainder = maxlen;
4143 FILEDESC_SLOCK(fdp);
4144 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4145 cdir = pwd->pwd_cdir;
4150 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4152 FILEDESC_SUNLOCK(fdp);
4154 free(efbuf, M_TEMP);
4159 * Get per-process current working directory.
4162 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4167 int error, error2, *name;
4171 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4172 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4173 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4178 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4179 error = kern_proc_cwd_out(p, &sb, maxlen);
4180 error2 = sbuf_finish(&sb);
4182 return (error != 0 ? error : error2);
4185 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4186 sysctl_kern_proc_cwd, "Process current working directory");
4190 * For the purposes of debugging, generate a human-readable string for the
4194 file_type_to_name(short type)
4222 case DTYPE_PROCDESC:
4224 case DTYPE_LINUXEFD:
4226 case DTYPE_LINUXTFD:
4234 * For the purposes of debugging, identify a process (if any, perhaps one of
4235 * many) that references the passed file in its file descriptor array. Return
4238 static struct proc *
4239 file_to_first_proc(struct file *fp)
4241 struct filedesc *fdp;
4245 FOREACH_PROC_IN_SYSTEM(p) {
4246 if (p->p_state == PRS_NEW)
4251 for (n = 0; n <= fdp->fd_lastfile; n++) {
4252 if (fp == fdp->fd_ofiles[n].fde_file)
4260 db_print_file(struct file *fp, int header)
4262 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4266 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4267 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4268 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4270 p = file_to_first_proc(fp);
4271 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4272 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4273 fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4274 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4279 DB_SHOW_COMMAND(file, db_show_file)
4284 db_printf("usage: show file <addr>\n");
4287 fp = (struct file *)addr;
4288 db_print_file(fp, 1);
4291 DB_SHOW_COMMAND(files, db_show_files)
4293 struct filedesc *fdp;
4300 FOREACH_PROC_IN_SYSTEM(p) {
4301 if (p->p_state == PRS_NEW)
4303 if ((fdp = p->p_fd) == NULL)
4305 for (n = 0; n <= fdp->fd_lastfile; ++n) {
4306 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4308 db_print_file(fp, header);
4315 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4316 &maxfilesperproc, 0, "Maximum files allowed open per process");
4318 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4319 &maxfiles, 0, "Maximum number of files");
4321 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4322 &openfiles, 0, "System-wide number of open files");
4326 filelistinit(void *dummy)
4329 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4330 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4331 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4332 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4333 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4334 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4335 pwd_smr = uma_zone_get_smr(pwd_zone);
4336 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4338 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4340 /*-------------------------------------------------------------------*/
4343 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4344 int flags, struct thread *td)
4351 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4359 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4367 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4375 badfo_kqfilter(struct file *fp, struct knote *kn)
4382 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4390 badfo_close(struct file *fp, struct thread *td)
4397 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4405 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4413 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4414 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4422 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4428 struct fileops badfileops = {
4429 .fo_read = badfo_readwrite,
4430 .fo_write = badfo_readwrite,
4431 .fo_truncate = badfo_truncate,
4432 .fo_ioctl = badfo_ioctl,
4433 .fo_poll = badfo_poll,
4434 .fo_kqfilter = badfo_kqfilter,
4435 .fo_stat = badfo_stat,
4436 .fo_close = badfo_close,
4437 .fo_chmod = badfo_chmod,
4438 .fo_chown = badfo_chown,
4439 .fo_sendfile = badfo_sendfile,
4440 .fo_fill_kinfo = badfo_fill_kinfo,
4444 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4445 int flags, struct thread *td)
4448 return (EOPNOTSUPP);
4452 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4460 invfo_ioctl(struct file *fp, u_long com, void *data,
4461 struct ucred *active_cred, struct thread *td)
4468 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4472 return (poll_no_poll(events));
4476 invfo_kqfilter(struct file *fp, struct knote *kn)
4483 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4491 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4499 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4500 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4507 /*-------------------------------------------------------------------*/
4510 * File Descriptor pseudo-device driver (/dev/fd/).
4512 * Opening minor device N dup()s the file (if any) connected to file
4513 * descriptor N belonging to the calling process. Note that this driver
4514 * consists of only the ``open()'' routine, because all subsequent
4515 * references to this file will be direct to the other driver.
4517 * XXX: we could give this one a cloning event handler if necessary.
4522 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4526 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4527 * the file descriptor being sought for duplication. The error
4528 * return ensures that the vnode for this device will be released
4529 * by vn_open. Open will detect this special error and take the
4530 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4531 * will simply report the error.
4533 td->td_dupfd = dev2unit(dev);
4537 static struct cdevsw fildesc_cdevsw = {
4538 .d_version = D_VERSION,
4544 fildesc_drvinit(void *unused)
4548 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4549 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4550 make_dev_alias(dev, "stdin");
4551 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4552 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4553 make_dev_alias(dev, "stdout");
4554 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4555 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4556 make_dev_alias(dev, "stderr");
4559 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);