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>
67 #include <sys/protosw.h>
68 #include <sys/racct.h>
69 #include <sys/resourcevar.h>
71 #include <sys/signalvar.h>
76 #include <sys/syscallsubr.h>
77 #include <sys/sysctl.h>
78 #include <sys/sysproto.h>
79 #include <sys/unistd.h>
81 #include <sys/vnode.h>
82 #include <sys/ktrace.h>
86 #include <security/audit/audit.h>
93 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
94 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
95 static MALLOC_DEFINE(M_PWDDESC, "pwddesc", "Pwd descriptors");
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 __read_mostly uma_zone_t pwd_zone;
108 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
109 struct thread *td, bool holdleaders, bool audit);
110 static int fd_first_free(struct filedesc *fdp, int low, int size);
111 static void fdgrowtable(struct filedesc *fdp, int nfd);
112 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
113 static void fdunused(struct filedesc *fdp, int fd);
114 static void fdused(struct filedesc *fdp, int fd);
115 static int getmaxfd(struct thread *td);
116 static u_long *filecaps_copy_prep(const struct filecaps *src);
117 static void filecaps_copy_finish(const struct filecaps *src,
118 struct filecaps *dst, u_long *ioctls);
119 static u_long *filecaps_free_prep(struct filecaps *fcaps);
120 static void filecaps_free_finish(u_long *ioctls);
122 static struct pwd *pwd_alloc(void);
127 * - An array of open file descriptors (fd_ofiles)
128 * - An array of file flags (fd_ofileflags)
129 * - A bitmap recording which descriptors are in use (fd_map)
131 * A process starts out with NDFILE descriptors. The value of NDFILE has
132 * been selected based the historical limit of 20 open files, and an
133 * assumption that the majority of processes, especially short-lived
134 * processes like shells, will never need more.
136 * If this initial allocation is exhausted, a larger descriptor table and
137 * map are allocated dynamically, and the pointers in the process's struct
138 * filedesc are updated to point to those. This is repeated every time
139 * the process runs out of file descriptors (provided it hasn't hit its
142 * Since threads may hold references to individual descriptor table
143 * entries, the tables are never freed. Instead, they are placed on a
144 * linked list and freed only when the struct filedesc is released.
147 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
148 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
149 #define NDSLOT(x) ((x) / NDENTRIES)
150 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
151 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
154 * SLIST entry used to keep track of ofiles which must be reclaimed when
158 struct fdescenttbl *ft_table;
159 SLIST_ENTRY(freetable) ft_next;
163 * Initial allocation: a filedesc structure + the head of SLIST used to
164 * keep track of old ofiles + enough space for NDFILE descriptors.
167 struct fdescenttbl0 {
169 struct filedescent fdt_ofiles[NDFILE];
173 struct filedesc fd_fd;
174 SLIST_HEAD(, freetable) fd_free;
175 struct fdescenttbl0 fd_dfiles;
176 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
180 * Descriptor management.
182 static int __exclusive_cache_line openfiles; /* actual number of open files */
183 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
184 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
187 * If low >= size, just return low. Otherwise find the first zero bit in the
188 * given bitmap, starting at low and not exceeding size - 1. Return size if
192 fd_first_free(struct filedesc *fdp, int low, int size)
194 NDSLOTTYPE *map = fdp->fd_map;
202 if (low % NDENTRIES) {
203 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
204 if ((mask &= ~map[off]) != 0UL)
205 return (off * NDENTRIES + ffsl(mask) - 1);
208 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
209 if (map[off] != ~0UL)
210 return (off * NDENTRIES + ffsl(~map[off]) - 1);
215 * Find the last used fd.
217 * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
218 * Otherwise use fdlastfile.
221 fdlastfile_single(struct filedesc *fdp)
223 NDSLOTTYPE *map = fdp->fd_map;
226 off = NDSLOT(fdp->fd_nfiles - 1);
227 for (minoff = NDSLOT(0); off >= minoff; --off)
229 return (off * NDENTRIES + flsl(map[off]) - 1);
234 fdlastfile(struct filedesc *fdp)
237 FILEDESC_LOCK_ASSERT(fdp);
238 return (fdlastfile_single(fdp));
242 fdisused(struct filedesc *fdp, int fd)
245 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
246 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
248 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
252 * Mark a file descriptor as used.
255 fdused_init(struct filedesc *fdp, int fd)
258 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
260 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
264 fdused(struct filedesc *fdp, int fd)
267 FILEDESC_XLOCK_ASSERT(fdp);
269 fdused_init(fdp, 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;
293 * Free a file descriptor.
295 * Avoid some work if fdp is about to be destroyed.
298 fdefree_last(struct filedescent *fde)
301 filecaps_free(&fde->fde_caps);
305 fdfree(struct filedesc *fdp, int fd)
307 struct filedescent *fde;
309 FILEDESC_XLOCK_ASSERT(fdp);
310 fde = &fdp->fd_ofiles[fd];
312 seqc_write_begin(&fde->fde_seqc);
314 fde->fde_file = NULL;
316 seqc_write_end(&fde->fde_seqc);
323 * System calls on descriptors.
325 #ifndef _SYS_SYSPROTO_H_
326 struct getdtablesize_args {
332 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
338 td->td_retval[0] = getmaxfd(td);
340 PROC_LOCK(td->td_proc);
341 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
342 PROC_UNLOCK(td->td_proc);
343 if (lim < td->td_retval[0])
344 td->td_retval[0] = lim;
350 * Duplicate a file descriptor to a particular value.
352 * Note: keep in mind that a potential race condition exists when closing
353 * descriptors from a shared descriptor table (via rfork).
355 #ifndef _SYS_SYSPROTO_H_
363 sys_dup2(struct thread *td, struct dup2_args *uap)
366 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
370 * Duplicate a file descriptor.
372 #ifndef _SYS_SYSPROTO_H_
379 sys_dup(struct thread *td, struct dup_args *uap)
382 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
386 * The file control system call.
388 #ifndef _SYS_SYSPROTO_H_
397 sys_fcntl(struct thread *td, struct fcntl_args *uap)
400 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
404 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
418 * Convert old flock structure to new.
420 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
421 fl.l_start = ofl.l_start;
422 fl.l_len = ofl.l_len;
423 fl.l_pid = ofl.l_pid;
424 fl.l_type = ofl.l_type;
425 fl.l_whence = ofl.l_whence;
439 arg1 = (intptr_t)&fl;
445 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
446 arg1 = (intptr_t)&fl;
454 error = kern_fcntl(td, fd, newcmd, arg1);
457 if (cmd == F_OGETLK) {
458 ofl.l_start = fl.l_start;
459 ofl.l_len = fl.l_len;
460 ofl.l_pid = fl.l_pid;
461 ofl.l_type = fl.l_type;
462 ofl.l_whence = fl.l_whence;
463 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
464 } else if (cmd == F_GETLK) {
465 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
471 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
473 struct filedesc *fdp;
475 struct file *fp, *fp2;
476 struct filedescent *fde;
480 int error, flg, seals, tmp;
494 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
497 case F_DUPFD_CLOEXEC:
499 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
504 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
507 case F_DUP2FD_CLOEXEC:
509 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
515 fde = fdeget_locked(fdp, fd);
518 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
521 FILEDESC_SUNLOCK(fdp);
527 fde = fdeget_locked(fdp, fd);
529 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
530 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
533 FILEDESC_XUNLOCK(fdp);
537 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
540 td->td_retval[0] = OFLAGS(fp->f_flag);
545 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
548 if (fp->f_ops == &path_fileops) {
554 tmp = flg = fp->f_flag;
556 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
557 } while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
558 tmp = fp->f_flag & FNONBLOCK;
559 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
564 tmp = fp->f_flag & FASYNC;
565 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
570 atomic_clear_int(&fp->f_flag, FNONBLOCK);
572 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
577 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
580 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
582 td->td_retval[0] = tmp;
587 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
591 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
596 error = priv_check(td, PRIV_NFS_LOCKD);
604 /* FALLTHROUGH F_SETLK */
608 flp = (struct flock *)arg;
609 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
614 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
617 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
623 if (flp->l_whence == SEEK_CUR) {
624 foffset = foffset_get(fp);
627 foffset > OFF_MAX - flp->l_start)) {
632 flp->l_start += foffset;
636 switch (flp->l_type) {
638 if ((fp->f_flag & FREAD) == 0) {
642 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
643 PROC_LOCK(p->p_leader);
644 p->p_leader->p_flag |= P_ADVLOCK;
645 PROC_UNLOCK(p->p_leader);
647 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
651 if ((fp->f_flag & FWRITE) == 0) {
655 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
656 PROC_LOCK(p->p_leader);
657 p->p_leader->p_flag |= P_ADVLOCK;
658 PROC_UNLOCK(p->p_leader);
660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
664 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
668 if (flg != F_REMOTE) {
672 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
673 F_UNLCKSYS, flp, flg);
679 if (error != 0 || flp->l_type == F_UNLCK ||
680 flp->l_type == F_UNLCKSYS) {
686 * Check for a race with close.
688 * The vnode is now advisory locked (or unlocked, but this case
689 * is not really important) as the caller requested.
690 * We had to drop the filedesc lock, so we need to recheck if
691 * the descriptor is still valid, because if it was closed
692 * in the meantime we need to remove advisory lock from the
693 * vnode - close on any descriptor leading to an advisory
694 * locked vnode, removes that lock.
695 * We will return 0 on purpose in that case, as the result of
696 * successful advisory lock might have been externally visible
697 * already. This is fine - effectively we pretend to the caller
698 * that the closing thread was a bit slower and that the
699 * advisory lock succeeded before the close.
701 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
707 flp->l_whence = SEEK_SET;
710 flp->l_type = F_UNLCK;
711 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
712 F_UNLCK, flp, F_POSIX);
719 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
722 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
727 flp = (struct flock *)arg;
728 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
729 flp->l_type != F_UNLCK) {
734 if (flp->l_whence == SEEK_CUR) {
735 foffset = foffset_get(fp);
736 if ((flp->l_start > 0 &&
737 foffset > OFF_MAX - flp->l_start) ||
739 foffset < OFF_MIN - flp->l_start)) {
744 flp->l_start += foffset;
747 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
753 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
756 error = fo_add_seals(fp, arg);
761 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
764 if (fo_get_seals(fp, &seals) == 0)
765 td->td_retval[0] = seals;
772 arg = arg ? 128 * 1024: 0;
775 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
778 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
784 if (vp->v_type != VREG) {
791 * Exclusive lock synchronizes against f_seqcount reads and
792 * writes in sequential_heuristic().
794 error = vn_lock(vp, LK_EXCLUSIVE);
800 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
801 arg = MIN(arg, INT_MAX - bsize + 1);
802 fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
803 (arg + bsize - 1) / bsize);
804 atomic_set_int(&fp->f_flag, FRDAHEAD);
806 atomic_clear_int(&fp->f_flag, FRDAHEAD);
814 * Check if the vnode is part of a union stack (either the
815 * "union" flag from mount(2) or unionfs).
817 * Prior to introduction of this op libc's readdir would call
818 * fstatfs(2), in effect unnecessarily copying kilobytes of
819 * data just to check fs name and a mount flag.
821 * Fixing the code to handle everything in the kernel instead
822 * is a non-trivial endeavor and has low priority, thus this
823 * horrible kludge facilitates the current behavior in a much
824 * cheaper manner until someone(tm) sorts this out.
826 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
829 if (fp->f_type != DTYPE_VNODE) {
836 * Since we don't prevent dooming the vnode even non-null mp
837 * found can become immediately stale. This is tolerable since
838 * mount points are type-stable (providing safe memory access)
839 * and any vfs op on this vnode going forward will return an
840 * error (meaning return value in this case is meaningless).
842 mp = atomic_load_ptr(&vp->v_mount);
843 if (__predict_false(mp == NULL)) {
848 td->td_retval[0] = 0;
849 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
850 mp->mnt_flag & MNT_UNION)
851 td->td_retval[0] = 1;
863 getmaxfd(struct thread *td)
866 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
870 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
873 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
875 struct filedesc *fdp;
876 struct filedescent *oldfde, *newfde;
878 struct file *delfp, *oldfp;
879 u_long *oioctls, *nioctls;
886 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
887 MPASS(mode < FDDUP_LASTMODE);
890 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
893 * Verify we have a valid descriptor to dup from and possibly to
894 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
895 * return EINVAL when the new descriptor is out of bounds.
900 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
901 maxfd = getmaxfd(td);
903 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
907 if (fget_locked(fdp, old) == NULL)
909 if (mode == FDDUP_FIXED && old == new) {
910 td->td_retval[0] = new;
911 if (flags & FDDUP_FLAG_CLOEXEC)
912 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
917 oldfde = &fdp->fd_ofiles[old];
918 oldfp = oldfde->fde_file;
923 * If the caller specified a file descriptor, make sure the file
924 * table is large enough to hold it, and grab it. Otherwise, just
925 * allocate a new descriptor the usual way.
930 if ((error = fdalloc(td, new, &new)) != 0) {
936 if (new >= fdp->fd_nfiles) {
938 * The resource limits are here instead of e.g.
939 * fdalloc(), because the file descriptor table may be
940 * shared between processes, so we can't really use
941 * racct_add()/racct_sub(). Instead of counting the
942 * number of actually allocated descriptors, just put
943 * the limit on the size of the file descriptor table.
946 if (RACCT_ENABLED()) {
947 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
955 fdgrowtable_exp(fdp, new + 1);
957 if (!fdisused(fdp, new))
961 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
964 KASSERT(old != new, ("new fd is same as old"));
966 /* Refetch oldfde because the table may have grown and old one freed. */
967 oldfde = &fdp->fd_ofiles[old];
968 KASSERT(oldfp == oldfde->fde_file,
969 ("fdt_ofiles shift from growth observed at fd %d",
972 newfde = &fdp->fd_ofiles[new];
973 delfp = newfde->fde_file;
975 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
978 * Duplicate the source descriptor.
981 seqc_write_begin(&newfde->fde_seqc);
983 oioctls = filecaps_free_prep(&newfde->fde_caps);
984 memcpy(newfde, oldfde, fde_change_size);
985 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
987 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
988 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
990 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
992 seqc_write_end(&newfde->fde_seqc);
994 td->td_retval[0] = new;
999 (void) closefp(fdp, new, delfp, td, true, false);
1000 FILEDESC_UNLOCK_ASSERT(fdp);
1003 FILEDESC_XUNLOCK(fdp);
1006 filecaps_free_finish(oioctls);
1011 sigiofree(struct sigio *sigio)
1013 crfree(sigio->sio_ucred);
1014 free(sigio, M_SIGIO);
1017 static struct sigio *
1018 funsetown_locked(struct sigio *sigio)
1023 SIGIO_ASSERT_LOCKED();
1027 *sigio->sio_myref = NULL;
1028 if (sigio->sio_pgid < 0) {
1029 pg = sigio->sio_pgrp;
1031 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1034 p = sigio->sio_proc;
1036 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1043 * If sigio is on the list associated with a process or process group,
1044 * disable signalling from the device, remove sigio from the list and
1048 funsetown(struct sigio **sigiop)
1050 struct sigio *sigio;
1052 /* Racy check, consumers must provide synchronization. */
1053 if (*sigiop == NULL)
1057 sigio = funsetown_locked(*sigiop);
1064 * Free a list of sigio structures. The caller must ensure that new sigio
1065 * structures cannot be added after this point. For process groups this is
1066 * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1070 funsetownlst(struct sigiolst *sigiolst)
1074 struct sigio *sigio, *tmp;
1077 sigio = SLIST_FIRST(sigiolst);
1085 sigio = SLIST_FIRST(sigiolst);
1086 if (sigio == NULL) {
1092 * Every entry of the list should belong to a single proc or pgrp.
1094 if (sigio->sio_pgid < 0) {
1095 pg = sigio->sio_pgrp;
1096 sx_assert(&proctree_lock, SX_XLOCKED);
1098 } else /* if (sigio->sio_pgid > 0) */ {
1099 p = sigio->sio_proc;
1101 KASSERT((p->p_flag & P_WEXIT) != 0,
1102 ("%s: process %p is not exiting", __func__, p));
1105 SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1106 *sigio->sio_myref = NULL;
1108 KASSERT(sigio->sio_pgid < 0,
1109 ("Proc sigio in pgrp sigio list"));
1110 KASSERT(sigio->sio_pgrp == pg,
1111 ("Bogus pgrp in sigio list"));
1112 } else /* if (p != NULL) */ {
1113 KASSERT(sigio->sio_pgid > 0,
1114 ("Pgrp sigio in proc sigio list"));
1115 KASSERT(sigio->sio_proc == p,
1116 ("Bogus proc in sigio list"));
1126 SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1131 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1133 * After permission checking, add a sigio structure to the sigio list for
1134 * the process or process group.
1137 fsetown(pid_t pgid, struct sigio **sigiop)
1141 struct sigio *osigio, *sigio;
1149 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1150 sigio->sio_pgid = pgid;
1151 sigio->sio_ucred = crhold(curthread->td_ucred);
1152 sigio->sio_myref = sigiop;
1156 ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1158 osigio = funsetown_locked(*sigiop);
1162 if ((proc->p_flag & P_WEXIT) != 0) {
1164 } else if (proc->p_session !=
1165 curthread->td_proc->p_session) {
1167 * Policy - Don't allow a process to FSETOWN a
1168 * process in another session.
1170 * Remove this test to allow maximum flexibility
1171 * or restrict FSETOWN to the current process or
1172 * process group for maximum safety.
1176 sigio->sio_proc = proc;
1177 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1182 } else /* if (pgid < 0) */ {
1183 sx_slock(&proctree_lock);
1185 osigio = funsetown_locked(*sigiop);
1186 pgrp = pgfind(-pgid);
1190 if (pgrp->pg_session != curthread->td_proc->p_session) {
1192 * Policy - Don't allow a process to FSETOWN a
1193 * process in another session.
1195 * Remove this test to allow maximum flexibility
1196 * or restrict FSETOWN to the current process or
1197 * process group for maximum safety.
1201 sigio->sio_pgrp = pgrp;
1202 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1207 sx_sunlock(&proctree_lock);
1218 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1221 fgetown(struct sigio **sigiop)
1226 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1232 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1237 FILEDESC_XLOCK_ASSERT(fdp);
1240 * We now hold the fp reference that used to be owned by the
1241 * descriptor array. We have to unlock the FILEDESC *AFTER*
1242 * knote_fdclose to prevent a race of the fd getting opened, a knote
1243 * added, and deleteing a knote for the new fd.
1245 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1246 knote_fdclose(td, fd);
1249 * We need to notify mqueue if the object is of type mqueue.
1251 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1252 mq_fdclose(td, fd, fp);
1253 FILEDESC_XUNLOCK(fdp);
1256 if (AUDITING_TD(td) && audit)
1257 audit_sysclose(td, fd, fp);
1259 error = closef(fp, td);
1262 * All paths leading up to closefp() will have already removed or
1263 * replaced the fd in the filedesc table, so a restart would not
1264 * operate on the same file.
1266 if (error == ERESTART)
1273 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1274 bool holdleaders, bool audit)
1278 FILEDESC_XLOCK_ASSERT(fdp);
1281 if (td->td_proc->p_fdtol != NULL) {
1283 * Ask fdfree() to sleep to ensure that all relevant
1284 * process leaders can be traversed in closef().
1286 fdp->fd_holdleaderscount++;
1288 holdleaders = false;
1292 error = closefp_impl(fdp, fd, fp, td, audit);
1294 FILEDESC_XLOCK(fdp);
1295 fdp->fd_holdleaderscount--;
1296 if (fdp->fd_holdleaderscount == 0 &&
1297 fdp->fd_holdleaderswakeup != 0) {
1298 fdp->fd_holdleaderswakeup = 0;
1299 wakeup(&fdp->fd_holdleaderscount);
1301 FILEDESC_XUNLOCK(fdp);
1307 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1308 bool holdleaders, bool audit)
1311 FILEDESC_XLOCK_ASSERT(fdp);
1313 if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1314 return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1316 return (closefp_impl(fdp, fd, fp, td, audit));
1321 * Close a file descriptor.
1323 #ifndef _SYS_SYSPROTO_H_
1330 sys_close(struct thread *td, struct close_args *uap)
1333 return (kern_close(td, uap->fd));
1337 kern_close(struct thread *td, int fd)
1339 struct filedesc *fdp;
1342 fdp = td->td_proc->p_fd;
1344 FILEDESC_XLOCK(fdp);
1345 if ((fp = fget_locked(fdp, fd)) == NULL) {
1346 FILEDESC_XUNLOCK(fdp);
1351 /* closefp() drops the FILEDESC lock for us. */
1352 return (closefp(fdp, fd, fp, td, true, true));
1356 kern_close_range(struct thread *td, u_int lowfd, u_int highfd)
1358 struct filedesc *fdp;
1359 const struct fdescenttbl *fdt;
1364 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1365 * open should not be a usage error. From a close_range() perspective,
1366 * close_range(3, ~0U, 0) in the same scenario should also likely not
1367 * be a usage error as all fd above 3 are in-fact already closed.
1369 if (highfd < lowfd) {
1373 fdp = td->td_proc->p_fd;
1374 FILEDESC_XLOCK(fdp);
1375 fdt = atomic_load_ptr(&fdp->fd_files);
1376 highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1378 if (__predict_false(fd > highfd)) {
1382 fp = fdt->fdt_ofiles[fd].fde_file;
1388 (void) closefp(fdp, fd, fp, td, true, true);
1391 FILEDESC_XLOCK(fdp);
1392 fdt = atomic_load_ptr(&fdp->fd_files);
1397 FILEDESC_XUNLOCK(fdp);
1402 #ifndef _SYS_SYSPROTO_H_
1403 struct close_range_args {
1410 sys_close_range(struct thread *td, struct close_range_args *uap)
1413 AUDIT_ARG_FD(uap->lowfd);
1414 AUDIT_ARG_CMD(uap->highfd);
1415 AUDIT_ARG_FFLAGS(uap->flags);
1417 /* No flags currently defined */
1418 if (uap->flags != 0)
1420 return (kern_close_range(td, uap->lowfd, uap->highfd));
1423 #ifdef COMPAT_FREEBSD12
1425 * Close open file descriptors.
1427 #ifndef _SYS_SYSPROTO_H_
1428 struct freebsd12_closefrom_args {
1434 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1438 AUDIT_ARG_FD(uap->lowfd);
1441 * Treat negative starting file descriptor values identical to
1442 * closefrom(0) which closes all files.
1444 lowfd = MAX(0, uap->lowfd);
1445 return (kern_close_range(td, lowfd, ~0U));
1447 #endif /* COMPAT_FREEBSD12 */
1449 #if defined(COMPAT_43)
1451 * Return status information about a file descriptor.
1453 #ifndef _SYS_SYSPROTO_H_
1454 struct ofstat_args {
1461 ofstat(struct thread *td, struct ofstat_args *uap)
1467 error = kern_fstat(td, uap->fd, &ub);
1470 error = copyout(&oub, uap->sb, sizeof(oub));
1474 #endif /* COMPAT_43 */
1476 #if defined(COMPAT_FREEBSD11)
1478 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1481 struct freebsd11_stat osb;
1484 error = kern_fstat(td, uap->fd, &sb);
1487 error = freebsd11_cvtstat(&sb, &osb);
1489 error = copyout(&osb, uap->sb, sizeof(osb));
1492 #endif /* COMPAT_FREEBSD11 */
1495 * Return status information about a file descriptor.
1497 #ifndef _SYS_SYSPROTO_H_
1505 sys_fstat(struct thread *td, struct fstat_args *uap)
1510 error = kern_fstat(td, uap->fd, &ub);
1512 error = copyout(&ub, uap->sb, sizeof(ub));
1517 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1524 error = fget(td, fd, &cap_fstat_rights, &fp);
1525 if (__predict_false(error != 0))
1528 AUDIT_ARG_FILE(td->td_proc, fp);
1530 error = fo_stat(fp, sbp, td->td_ucred);
1532 #ifdef __STAT_TIME_T_EXT
1533 sbp->st_atim_ext = 0;
1534 sbp->st_mtim_ext = 0;
1535 sbp->st_ctim_ext = 0;
1536 sbp->st_btim_ext = 0;
1539 if (KTRPOINT(td, KTR_STRUCT))
1540 ktrstat_error(sbp, error);
1545 #if defined(COMPAT_FREEBSD11)
1547 * Return status information about a file descriptor.
1549 #ifndef _SYS_SYSPROTO_H_
1550 struct freebsd11_nfstat_args {
1557 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1563 error = kern_fstat(td, uap->fd, &ub);
1566 error = freebsd11_cvtnstat(&ub, &nub);
1568 error = copyout(&nub, uap->sb, sizeof(nub));
1571 #endif /* COMPAT_FREEBSD11 */
1574 * Return pathconf information about a file descriptor.
1576 #ifndef _SYS_SYSPROTO_H_
1577 struct fpathconf_args {
1584 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1589 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1591 td->td_retval[0] = value;
1596 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1602 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1606 if (name == _PC_ASYNC_IO) {
1607 *valuep = _POSIX_ASYNCHRONOUS_IO;
1612 vn_lock(vp, LK_SHARED | LK_RETRY);
1613 error = VOP_PATHCONF(vp, name, valuep);
1615 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1616 if (name != _PC_PIPE_BUF) {
1631 * Copy filecaps structure allocating memory for ioctls array if needed.
1633 * The last parameter indicates whether the fdtable is locked. If it is not and
1634 * ioctls are encountered, copying fails and the caller must lock the table.
1636 * Note that if the table was not locked, the caller has to check the relevant
1637 * sequence counter to determine whether the operation was successful.
1640 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1644 if (src->fc_ioctls != NULL && !locked)
1646 memcpy(dst, src, sizeof(*src));
1647 if (src->fc_ioctls == NULL)
1650 KASSERT(src->fc_nioctls > 0,
1651 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1653 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1654 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1655 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1660 filecaps_copy_prep(const struct filecaps *src)
1665 if (__predict_true(src->fc_ioctls == NULL))
1668 KASSERT(src->fc_nioctls > 0,
1669 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1671 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1672 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1677 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1683 if (__predict_true(src->fc_ioctls == NULL)) {
1684 MPASS(ioctls == NULL);
1688 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1689 dst->fc_ioctls = ioctls;
1690 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1694 * Move filecaps structure to the new place and clear the old place.
1697 filecaps_move(struct filecaps *src, struct filecaps *dst)
1701 bzero(src, sizeof(*src));
1705 * Fill the given filecaps structure with full rights.
1708 filecaps_fill(struct filecaps *fcaps)
1711 CAP_ALL(&fcaps->fc_rights);
1712 fcaps->fc_ioctls = NULL;
1713 fcaps->fc_nioctls = -1;
1714 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1718 * Free memory allocated within filecaps structure.
1721 filecaps_free(struct filecaps *fcaps)
1724 free(fcaps->fc_ioctls, M_FILECAPS);
1725 bzero(fcaps, sizeof(*fcaps));
1729 filecaps_free_prep(struct filecaps *fcaps)
1733 ioctls = fcaps->fc_ioctls;
1734 bzero(fcaps, sizeof(*fcaps));
1739 filecaps_free_finish(u_long *ioctls)
1742 free(ioctls, M_FILECAPS);
1746 * Validate the given filecaps structure.
1749 filecaps_validate(const struct filecaps *fcaps, const char *func)
1752 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1753 ("%s: invalid rights", func));
1754 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1755 ("%s: invalid fcntls", func));
1756 KASSERT(fcaps->fc_fcntls == 0 ||
1757 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1758 ("%s: fcntls without CAP_FCNTL", func));
1759 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1760 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1761 ("%s: invalid ioctls", func));
1762 KASSERT(fcaps->fc_nioctls == 0 ||
1763 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1764 ("%s: ioctls without CAP_IOCTL", func));
1768 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1772 FILEDESC_XLOCK_ASSERT(fdp);
1774 nfd1 = fdp->fd_nfiles * 2;
1777 fdgrowtable(fdp, nfd1);
1781 * Grow the file table to accommodate (at least) nfd descriptors.
1784 fdgrowtable(struct filedesc *fdp, int nfd)
1786 struct filedesc0 *fdp0;
1787 struct freetable *ft;
1788 struct fdescenttbl *ntable;
1789 struct fdescenttbl *otable;
1790 int nnfiles, onfiles;
1791 NDSLOTTYPE *nmap, *omap;
1793 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1795 /* save old values */
1796 onfiles = fdp->fd_nfiles;
1797 otable = fdp->fd_files;
1800 /* compute the size of the new table */
1801 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1802 if (nnfiles <= onfiles)
1803 /* the table is already large enough */
1807 * Allocate a new table. We need enough space for the number of
1808 * entries, file entries themselves and the struct freetable we will use
1809 * when we decommission the table and place it on the freelist.
1810 * We place the struct freetable in the middle so we don't have
1811 * to worry about padding.
1813 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1814 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1815 sizeof(struct freetable),
1816 M_FILEDESC, M_ZERO | M_WAITOK);
1817 /* copy the old data */
1818 ntable->fdt_nfiles = nnfiles;
1819 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1820 onfiles * sizeof(ntable->fdt_ofiles[0]));
1823 * Allocate a new map only if the old is not large enough. It will
1824 * grow at a slower rate than the table as it can map more
1825 * entries than the table can hold.
1827 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1828 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1830 /* copy over the old data and update the pointer */
1831 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1836 * Make sure that ntable is correctly initialized before we replace
1837 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1840 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1843 * Free the old file table when not shared by other threads or processes.
1844 * The old file table is considered to be shared when either are true:
1845 * - The process has more than one thread.
1846 * - The file descriptor table has been shared via fdshare().
1848 * When shared, the old file table will be placed on a freelist
1849 * which will be processed when the struct filedesc is released.
1851 * Note that if onfiles == NDFILE, we're dealing with the original
1852 * static allocation contained within (struct filedesc0 *)fdp,
1853 * which must not be freed.
1855 if (onfiles > NDFILE) {
1857 * Note we may be called here from fdinit while allocating a
1858 * table for a new process in which case ->p_fd points
1861 if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1862 free(otable, M_FILEDESC);
1864 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1865 fdp0 = (struct filedesc0 *)fdp;
1866 ft->ft_table = otable;
1867 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1871 * The map does not have the same possibility of threads still
1872 * holding references to it. So always free it as long as it
1873 * does not reference the original static allocation.
1875 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1876 free(omap, M_FILEDESC);
1880 * Allocate a file descriptor for the process.
1883 fdalloc(struct thread *td, int minfd, int *result)
1885 struct proc *p = td->td_proc;
1886 struct filedesc *fdp = p->p_fd;
1887 int fd, maxfd, allocfd;
1892 FILEDESC_XLOCK_ASSERT(fdp);
1894 if (fdp->fd_freefile > minfd)
1895 minfd = fdp->fd_freefile;
1897 maxfd = getmaxfd(td);
1900 * Search the bitmap for a free descriptor starting at minfd.
1901 * If none is found, grow the file table.
1903 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1904 if (__predict_false(fd >= maxfd))
1906 if (__predict_false(fd >= fdp->fd_nfiles)) {
1907 allocfd = min(fd * 2, maxfd);
1909 if (RACCT_ENABLED()) {
1910 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1916 * fd is already equal to first free descriptor >= minfd, so
1917 * we only need to grow the table and we are done.
1919 fdgrowtable_exp(fdp, allocfd);
1923 * Perform some sanity checks, then mark the file descriptor as
1924 * used and return it to the caller.
1926 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1927 ("invalid descriptor %d", fd));
1928 KASSERT(!fdisused(fdp, fd),
1929 ("fd_first_free() returned non-free descriptor"));
1930 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1931 ("file descriptor isn't free"));
1938 * Allocate n file descriptors for the process.
1941 fdallocn(struct thread *td, int minfd, int *fds, int n)
1943 struct proc *p = td->td_proc;
1944 struct filedesc *fdp = p->p_fd;
1947 FILEDESC_XLOCK_ASSERT(fdp);
1949 for (i = 0; i < n; i++)
1950 if (fdalloc(td, 0, &fds[i]) != 0)
1954 for (i--; i >= 0; i--)
1955 fdunused(fdp, fds[i]);
1963 * Create a new open file structure and allocate a file descriptor for the
1964 * process that refers to it. We add one reference to the file for the
1965 * descriptor table and one reference for resultfp. This is to prevent us
1966 * being preempted and the entry in the descriptor table closed after we
1967 * release the FILEDESC lock.
1970 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1971 struct filecaps *fcaps)
1976 MPASS(resultfp != NULL);
1977 MPASS(resultfd != NULL);
1979 error = _falloc_noinstall(td, &fp, 2);
1980 if (__predict_false(error != 0)) {
1984 error = finstall_refed(td, fp, &fd, flags, fcaps);
1985 if (__predict_false(error != 0)) {
1986 falloc_abort(td, fp);
1997 * Create a new open file structure without allocating a file descriptor.
2000 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2003 int maxuserfiles = maxfiles - (maxfiles / 20);
2005 static struct timeval lastfail;
2008 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2011 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2012 if ((openfiles_new >= maxuserfiles &&
2013 priv_check(td, PRIV_MAXFILES) != 0) ||
2014 openfiles_new >= maxfiles) {
2015 atomic_subtract_int(&openfiles, 1);
2016 if (ppsratecheck(&lastfail, &curfail, 1)) {
2017 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2018 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2022 fp = uma_zalloc(file_zone, M_WAITOK);
2023 bzero(fp, sizeof(*fp));
2024 refcount_init(&fp->f_count, n);
2025 fp->f_cred = crhold(td->td_ucred);
2026 fp->f_ops = &badfileops;
2032 falloc_abort(struct thread *td, struct file *fp)
2036 * For assertion purposes.
2038 refcount_init(&fp->f_count, 0);
2043 * Install a file in a file descriptor table.
2046 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2047 struct filecaps *fcaps)
2049 struct filedescent *fde;
2053 filecaps_validate(fcaps, __func__);
2054 FILEDESC_XLOCK_ASSERT(fdp);
2056 fde = &fdp->fd_ofiles[fd];
2058 seqc_write_begin(&fde->fde_seqc);
2061 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2063 filecaps_move(fcaps, &fde->fde_caps);
2065 filecaps_fill(&fde->fde_caps);
2067 seqc_write_end(&fde->fde_seqc);
2072 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2073 struct filecaps *fcaps)
2075 struct filedesc *fdp = td->td_proc->p_fd;
2080 FILEDESC_XLOCK(fdp);
2081 error = fdalloc(td, 0, fd);
2082 if (__predict_true(error == 0)) {
2083 _finstall(fdp, fp, *fd, flags, fcaps);
2085 FILEDESC_XUNLOCK(fdp);
2090 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2091 struct filecaps *fcaps)
2099 error = finstall_refed(td, fp, fd, flags, fcaps);
2100 if (__predict_false(error != 0)) {
2107 * Build a new filedesc structure from another.
2109 * If fdp is not NULL, return with it shared locked.
2112 fdinit(struct filedesc *fdp, bool prepfiles, int *lastfile)
2114 struct filedesc0 *newfdp0;
2115 struct filedesc *newfdp;
2118 MPASS(lastfile != NULL);
2120 MPASS(lastfile == NULL);
2122 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2123 newfdp = &newfdp0->fd_fd;
2125 /* Create the file descriptor table. */
2126 FILEDESC_LOCK_INIT(newfdp);
2127 refcount_init(&newfdp->fd_refcnt, 1);
2128 refcount_init(&newfdp->fd_holdcnt, 1);
2129 newfdp->fd_map = newfdp0->fd_dmap;
2130 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2131 newfdp->fd_files->fdt_nfiles = NDFILE;
2136 FILEDESC_SLOCK(fdp);
2138 FILEDESC_SUNLOCK(fdp);
2143 *lastfile = fdlastfile(fdp);
2144 if (*lastfile < newfdp->fd_nfiles)
2146 FILEDESC_SUNLOCK(fdp);
2147 fdgrowtable(newfdp, *lastfile + 1);
2148 FILEDESC_SLOCK(fdp);
2155 * Build a pwddesc structure from another.
2156 * Copy the current, root, and jail root vnode references.
2158 * If pdp is not NULL, return with it shared locked.
2161 pdinit(struct pwddesc *pdp, bool keeplock)
2163 struct pwddesc *newpdp;
2166 newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2168 PWDDESC_LOCK_INIT(newpdp);
2169 refcount_init(&newpdp->pd_refcount, 1);
2170 newpdp->pd_cmask = CMASK;
2173 newpwd = pwd_alloc();
2174 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2179 newpwd = pwd_hold_pwddesc(pdp);
2180 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2182 PWDDESC_XUNLOCK(pdp);
2187 * Hold either filedesc or pwddesc of the passed process.
2189 * The process lock is used to synchronize against the target exiting and
2192 * Clearing can be ilustrated in 3 steps:
2193 * 1. set the pointer to NULL. Either routine can race against it, hence
2195 * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2196 * race to either still see the pointer or find NULL. It is still safe to
2197 * grab a reference as clearing is stalled.
2198 * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2199 * guaranteed to see NULL, making it safe to finish clearing
2201 static struct filedesc *
2202 fdhold(struct proc *p)
2204 struct filedesc *fdp;
2206 PROC_LOCK_ASSERT(p, MA_OWNED);
2207 fdp = atomic_load_ptr(&p->p_fd);
2209 refcount_acquire(&fdp->fd_holdcnt);
2213 static struct pwddesc *
2214 pdhold(struct proc *p)
2216 struct pwddesc *pdp;
2218 PROC_LOCK_ASSERT(p, MA_OWNED);
2219 pdp = atomic_load_ptr(&p->p_pd);
2221 refcount_acquire(&pdp->pd_refcount);
2226 fddrop(struct filedesc *fdp)
2229 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2230 if (refcount_release(&fdp->fd_holdcnt) == 0)
2234 FILEDESC_LOCK_DESTROY(fdp);
2235 uma_zfree(filedesc0_zone, fdp);
2239 pddrop(struct pwddesc *pdp)
2243 if (refcount_release_if_not_last(&pdp->pd_refcount))
2247 if (refcount_release(&pdp->pd_refcount) == 0) {
2248 PWDDESC_XUNLOCK(pdp);
2251 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2253 PWDDESC_XUNLOCK(pdp);
2256 PWDDESC_LOCK_DESTROY(pdp);
2257 free(pdp, M_PWDDESC);
2261 * Share a filedesc structure.
2264 fdshare(struct filedesc *fdp)
2267 refcount_acquire(&fdp->fd_refcnt);
2272 * Share a pwddesc structure.
2275 pdshare(struct pwddesc *pdp)
2277 refcount_acquire(&pdp->pd_refcount);
2282 * Unshare a filedesc structure, if necessary by making a copy
2285 fdunshare(struct thread *td)
2287 struct filedesc *tmp;
2288 struct proc *p = td->td_proc;
2290 if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2293 tmp = fdcopy(p->p_fd);
2299 * Unshare a pwddesc structure.
2302 pdunshare(struct thread *td)
2304 struct pwddesc *pdp;
2309 if (p->p_pd->pd_refcount == 1)
2312 pdp = pdcopy(p->p_pd);
2318 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2319 * this is to ease callers, not catch errors.
2322 fdcopy(struct filedesc *fdp)
2324 struct filedesc *newfdp;
2325 struct filedescent *nfde, *ofde;
2330 newfdp = fdinit(fdp, true, &lastfile);
2331 /* copy all passable descriptors (i.e. not kqueue) */
2332 newfdp->fd_freefile = -1;
2333 for (i = 0; i <= lastfile; ++i) {
2334 ofde = &fdp->fd_ofiles[i];
2335 if (ofde->fde_file == NULL ||
2336 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2337 !fhold(ofde->fde_file)) {
2338 if (newfdp->fd_freefile == -1)
2339 newfdp->fd_freefile = i;
2342 nfde = &newfdp->fd_ofiles[i];
2344 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2345 fdused_init(newfdp, i);
2347 if (newfdp->fd_freefile == -1)
2348 newfdp->fd_freefile = i;
2349 FILEDESC_SUNLOCK(fdp);
2354 * Copy a pwddesc structure.
2357 pdcopy(struct pwddesc *pdp)
2359 struct pwddesc *newpdp;
2363 newpdp = pdinit(pdp, true);
2364 newpdp->pd_cmask = pdp->pd_cmask;
2365 PWDDESC_XUNLOCK(pdp);
2370 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2371 * one of processes using it exits) and the table used to be shared.
2374 fdclearlocks(struct thread *td)
2376 struct filedesc *fdp;
2377 struct filedesc_to_leader *fdtol;
2387 MPASS(fdtol != NULL);
2389 FILEDESC_XLOCK(fdp);
2390 KASSERT(fdtol->fdl_refcount > 0,
2391 ("filedesc_to_refcount botch: fdl_refcount=%d",
2392 fdtol->fdl_refcount));
2393 if (fdtol->fdl_refcount == 1 &&
2394 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2395 lastfile = fdlastfile(fdp);
2396 for (i = 0; i <= lastfile; i++) {
2397 fp = fdp->fd_ofiles[i].fde_file;
2398 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2401 FILEDESC_XUNLOCK(fdp);
2402 lf.l_whence = SEEK_SET;
2405 lf.l_type = F_UNLCK;
2407 (void) VOP_ADVLOCK(vp,
2408 (caddr_t)p->p_leader, F_UNLCK,
2410 FILEDESC_XLOCK(fdp);
2415 if (fdtol->fdl_refcount == 1) {
2416 if (fdp->fd_holdleaderscount > 0 &&
2417 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2419 * close() or kern_dup() has cleared a reference
2420 * in a shared file descriptor table.
2422 fdp->fd_holdleaderswakeup = 1;
2423 sx_sleep(&fdp->fd_holdleaderscount,
2424 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2427 if (fdtol->fdl_holdcount > 0) {
2429 * Ensure that fdtol->fdl_leader remains
2430 * valid in closef().
2432 fdtol->fdl_wakeup = 1;
2433 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2438 fdtol->fdl_refcount--;
2439 if (fdtol->fdl_refcount == 0 &&
2440 fdtol->fdl_holdcount == 0) {
2441 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2442 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2446 FILEDESC_XUNLOCK(fdp);
2448 free(fdtol, M_FILEDESC_TO_LEADER);
2452 * Release a filedesc structure.
2455 fdescfree_fds(struct thread *td, struct filedesc *fdp)
2457 struct filedesc0 *fdp0;
2458 struct freetable *ft, *tft;
2459 struct filedescent *fde;
2463 KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2464 ("%s: fd table %p carries references", __func__, fdp));
2467 * Serialize with threads iterating over the table, if any.
2469 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2470 FILEDESC_XLOCK(fdp);
2471 FILEDESC_XUNLOCK(fdp);
2474 lastfile = fdlastfile_single(fdp);
2475 for (i = 0; i <= lastfile; i++) {
2476 fde = &fdp->fd_ofiles[i];
2480 (void) closef(fp, td);
2484 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2485 free(fdp->fd_map, M_FILEDESC);
2486 if (fdp->fd_nfiles > NDFILE)
2487 free(fdp->fd_files, M_FILEDESC);
2489 fdp0 = (struct filedesc0 *)fdp;
2490 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2491 free(ft->ft_table, M_FILEDESC);
2497 fdescfree(struct thread *td)
2500 struct filedesc *fdp;
2507 if (RACCT_ENABLED())
2508 racct_set_unlocked(p, RACCT_NOFILE, 0);
2511 if (p->p_fdtol != NULL)
2515 * Check fdhold for an explanation.
2517 atomic_store_ptr(&p->p_fd, NULL);
2518 atomic_thread_fence_seq_cst();
2519 PROC_WAIT_UNLOCKED(p);
2521 if (refcount_release(&fdp->fd_refcnt) == 0)
2524 fdescfree_fds(td, fdp);
2528 pdescfree(struct thread *td)
2531 struct pwddesc *pdp;
2538 * Check pdhold for an explanation.
2540 atomic_store_ptr(&p->p_pd, NULL);
2541 atomic_thread_fence_seq_cst();
2542 PROC_WAIT_UNLOCKED(p);
2548 * For setugid programs, we don't want to people to use that setugidness
2549 * to generate error messages which write to a file which otherwise would
2550 * otherwise be off-limits to the process. We check for filesystems where
2551 * the vnode can change out from under us after execve (like [lin]procfs).
2553 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2554 * sufficient. We also don't check for setugidness since we know we are.
2557 is_unsafe(struct file *fp)
2561 if (fp->f_type != DTYPE_VNODE)
2565 return ((vp->v_vflag & VV_PROCDEP) != 0);
2569 * Make this setguid thing safe, if at all possible.
2572 fdsetugidsafety(struct thread *td)
2574 struct filedesc *fdp;
2578 fdp = td->td_proc->p_fd;
2579 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2580 ("the fdtable should not be shared"));
2581 MPASS(fdp->fd_nfiles >= 3);
2582 for (i = 0; i <= 2; i++) {
2583 fp = fdp->fd_ofiles[i].fde_file;
2584 if (fp != NULL && is_unsafe(fp)) {
2585 FILEDESC_XLOCK(fdp);
2586 knote_fdclose(td, i);
2588 * NULL-out descriptor prior to close to avoid
2589 * a race while close blocks.
2592 FILEDESC_XUNLOCK(fdp);
2593 (void) closef(fp, td);
2599 * If a specific file object occupies a specific file descriptor, close the
2600 * file descriptor entry and drop a reference on the file object. This is a
2601 * convenience function to handle a subsequent error in a function that calls
2602 * falloc() that handles the race that another thread might have closed the
2603 * file descriptor out from under the thread creating the file object.
2606 fdclose(struct thread *td, struct file *fp, int idx)
2608 struct filedesc *fdp = td->td_proc->p_fd;
2610 FILEDESC_XLOCK(fdp);
2611 if (fdp->fd_ofiles[idx].fde_file == fp) {
2613 FILEDESC_XUNLOCK(fdp);
2616 FILEDESC_XUNLOCK(fdp);
2620 * Close any files on exec?
2623 fdcloseexec(struct thread *td)
2625 struct filedesc *fdp;
2626 struct filedescent *fde;
2630 fdp = td->td_proc->p_fd;
2631 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2632 ("the fdtable should not be shared"));
2633 lastfile = fdlastfile_single(fdp);
2634 for (i = 0; i <= lastfile; i++) {
2635 fde = &fdp->fd_ofiles[i];
2637 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2638 (fde->fde_flags & UF_EXCLOSE))) {
2639 FILEDESC_XLOCK(fdp);
2641 (void) closefp(fdp, i, fp, td, false, false);
2642 FILEDESC_UNLOCK_ASSERT(fdp);
2648 * It is unsafe for set[ug]id processes to be started with file
2649 * descriptors 0..2 closed, as these descriptors are given implicit
2650 * significance in the Standard C library. fdcheckstd() will create a
2651 * descriptor referencing /dev/null for each of stdin, stdout, and
2652 * stderr that is not already open.
2655 fdcheckstd(struct thread *td)
2657 struct filedesc *fdp;
2659 int i, error, devnull;
2661 fdp = td->td_proc->p_fd;
2662 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2663 ("the fdtable should not be shared"));
2664 MPASS(fdp->fd_nfiles >= 3);
2666 for (i = 0; i <= 2; i++) {
2667 if (fdp->fd_ofiles[i].fde_file != NULL)
2670 save = td->td_retval[0];
2671 if (devnull != -1) {
2672 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2674 error = kern_openat(td, AT_FDCWD, "/dev/null",
2675 UIO_SYSSPACE, O_RDWR, 0);
2677 devnull = td->td_retval[0];
2678 KASSERT(devnull == i, ("we didn't get our fd"));
2681 td->td_retval[0] = save;
2689 * Internal form of close. Decrement reference count on file structure.
2690 * Note: td may be NULL when closing a file that was being passed in a
2694 closef(struct file *fp, struct thread *td)
2698 struct filedesc_to_leader *fdtol;
2699 struct filedesc *fdp;
2704 * POSIX record locking dictates that any close releases ALL
2705 * locks owned by this process. This is handled by setting
2706 * a flag in the unlock to free ONLY locks obeying POSIX
2707 * semantics, and not to free BSD-style file locks.
2708 * If the descriptor was in a message, POSIX-style locks
2709 * aren't passed with the descriptor, and the thread pointer
2710 * will be NULL. Callers should be careful only to pass a
2711 * NULL thread pointer when there really is no owning
2712 * context that might have locks, or the locks will be
2715 if (fp->f_type == DTYPE_VNODE) {
2717 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2718 lf.l_whence = SEEK_SET;
2721 lf.l_type = F_UNLCK;
2722 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2723 F_UNLCK, &lf, F_POSIX);
2725 fdtol = td->td_proc->p_fdtol;
2726 if (fdtol != NULL) {
2728 * Handle special case where file descriptor table is
2729 * shared between multiple process leaders.
2731 fdp = td->td_proc->p_fd;
2732 FILEDESC_XLOCK(fdp);
2733 for (fdtol = fdtol->fdl_next;
2734 fdtol != td->td_proc->p_fdtol;
2735 fdtol = fdtol->fdl_next) {
2736 if ((fdtol->fdl_leader->p_flag &
2739 fdtol->fdl_holdcount++;
2740 FILEDESC_XUNLOCK(fdp);
2741 lf.l_whence = SEEK_SET;
2744 lf.l_type = F_UNLCK;
2746 (void) VOP_ADVLOCK(vp,
2747 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2749 FILEDESC_XLOCK(fdp);
2750 fdtol->fdl_holdcount--;
2751 if (fdtol->fdl_holdcount == 0 &&
2752 fdtol->fdl_wakeup != 0) {
2753 fdtol->fdl_wakeup = 0;
2757 FILEDESC_XUNLOCK(fdp);
2760 return (fdrop_close(fp, td));
2764 * Hack for file descriptor passing code.
2767 closef_nothread(struct file *fp)
2774 * Initialize the file pointer with the specified properties.
2776 * The ops are set with release semantics to be certain that the flags, type,
2777 * and data are visible when ops is. This is to prevent ops methods from being
2778 * called with bad data.
2781 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2786 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2790 finit_vnode(struct file *fp, u_int flag, void *data, struct fileops *ops)
2792 fp->f_seqcount[UIO_READ] = 1;
2793 fp->f_seqcount[UIO_WRITE] = 1;
2794 finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2799 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2800 struct file **fpp, struct filecaps *havecapsp)
2802 struct filedescent *fde;
2805 FILEDESC_LOCK_ASSERT(fdp);
2807 fde = fdeget_locked(fdp, fd);
2814 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2819 if (havecapsp != NULL)
2820 filecaps_copy(&fde->fde_caps, havecapsp, true);
2822 *fpp = fde->fde_file;
2830 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2831 struct file **fpp, struct filecaps *havecapsp)
2833 struct filedesc *fdp = td->td_proc->p_fd;
2835 #ifndef CAPABILITIES
2836 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2837 if (havecapsp != NULL && error == 0)
2838 filecaps_fill(havecapsp);
2845 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2849 if (havecapsp != NULL) {
2850 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2851 havecapsp, false)) {
2857 if (!fd_modified(fdp, fd, seq))
2866 FILEDESC_SLOCK(fdp);
2867 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2868 if (error == 0 && !fhold(*fpp))
2870 FILEDESC_SUNLOCK(fdp);
2877 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
2879 const struct filedescent *fde;
2880 const struct fdescenttbl *fdt;
2881 struct filedesc *fdp;
2884 const cap_rights_t *haverights;
2885 cap_rights_t rights;
2888 VFS_SMR_ASSERT_ENTERED();
2890 rights = *ndp->ni_rightsneeded;
2891 cap_rights_set_one(&rights, CAP_LOOKUP);
2893 fdp = curproc->p_fd;
2894 fdt = fdp->fd_files;
2895 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2897 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
2898 fde = &fdt->fdt_ofiles[fd];
2899 haverights = cap_rights_fde_inline(fde);
2901 if (__predict_false(fp == NULL))
2903 if (__predict_false(cap_check_inline_transient(haverights, &rights)))
2905 *fsearch = ((fp->f_flag & FSEARCH) != 0);
2907 if (__predict_false(vp == NULL)) {
2910 if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
2914 * Use an acquire barrier to force re-reading of fdt so it is
2915 * refreshed for verification.
2917 atomic_thread_fence_acq();
2918 fdt = fdp->fd_files;
2919 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2922 * If file descriptor doesn't have all rights,
2923 * all lookups relative to it must also be
2924 * strictly relative.
2926 * Not yet supported by fast path.
2929 if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
2930 ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
2931 ndp->ni_filecaps.fc_nioctls != -1) {
2933 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
2943 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
2945 const struct fdescenttbl *fdt;
2946 struct filedesc *fdp;
2950 VFS_SMR_ASSERT_ENTERED();
2952 fdp = curproc->p_fd;
2953 fdt = fdp->fd_files;
2954 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2956 fp = fdt->fdt_ofiles[fd].fde_file;
2957 if (__predict_false(fp == NULL))
2959 *fsearch = ((fp->f_flag & FSEARCH) != 0);
2961 if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
2965 * Use an acquire barrier to force re-reading of fdt so it is
2966 * refreshed for verification.
2968 atomic_thread_fence_acq();
2969 fdt = fdp->fd_files;
2970 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2972 filecaps_fill(&ndp->ni_filecaps);
2979 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2980 struct file **fpp, seqc_t *seqp)
2983 const struct filedescent *fde;
2985 const struct fdescenttbl *fdt;
2989 cap_rights_t haverights;
2993 fdt = fdp->fd_files;
2994 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2997 * Fetch the descriptor locklessly. We avoid fdrop() races by
2998 * never raising a refcount above 0. To accomplish this we have
2999 * to use a cmpset loop rather than an atomic_add. The descriptor
3000 * must be re-verified once we acquire a reference to be certain
3001 * that the identity is still correct and we did not lose a race
3002 * due to preemption.
3006 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3007 fde = &fdt->fdt_ofiles[fd];
3008 haverights = *cap_rights_fde_inline(fde);
3010 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
3013 fp = fdt->fdt_ofiles[fd].fde_file;
3018 error = cap_check_inline(&haverights, needrightsp);
3022 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3024 * Force a reload. Other thread could reallocate the
3025 * table before this fd was closed, so it is possible
3026 * that there is a stale fp pointer in cached version.
3028 fdt = atomic_load_ptr(&fdp->fd_files);
3032 * Use an acquire barrier to force re-reading of fdt so it is
3033 * refreshed for verification.
3035 atomic_thread_fence_acq();
3036 fdt = fdp->fd_files;
3038 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
3040 if (fp == fdt->fdt_ofiles[fd].fde_file)
3043 fdrop(fp, curthread);
3055 * See the comments in fget_unlocked_seq for an explanation of how this works.
3057 * This is a simplified variant which bails out to the aforementioned routine
3058 * if anything goes wrong. In practice this only happens when userspace is
3059 * racing with itself.
3062 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3066 const struct filedescent *fde;
3068 const struct fdescenttbl *fdt;
3072 const cap_rights_t *haverights;
3075 fdt = fdp->fd_files;
3076 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3079 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3080 fde = &fdt->fdt_ofiles[fd];
3081 haverights = cap_rights_fde_inline(fde);
3084 fp = fdt->fdt_ofiles[fd].fde_file;
3086 if (__predict_false(fp == NULL))
3089 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3092 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3096 * Use an acquire barrier to force re-reading of fdt so it is
3097 * refreshed for verification.
3099 atomic_thread_fence_acq();
3100 fdt = fdp->fd_files;
3102 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
3104 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3110 fdrop(fp, curthread);
3112 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
3116 * Translate fd -> file when the caller guarantees the file descriptor table
3117 * can't be changed by others.
3119 * Note this does not mean the file object itself is only visible to the caller,
3120 * merely that it wont disappear without having to be referenced.
3122 * Must be paired with fput_only_user.
3126 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3129 const struct filedescent *fde;
3130 const struct fdescenttbl *fdt;
3131 const cap_rights_t *haverights;
3135 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3137 if (__predict_false(fd >= fdp->fd_nfiles))
3140 fdt = fdp->fd_files;
3141 fde = &fdt->fdt_ofiles[fd];
3143 if (__predict_false(fp == NULL))
3145 MPASS(refcount_load(&fp->f_count) > 0);
3146 haverights = cap_rights_fde_inline(fde);
3147 error = cap_check_inline(haverights, needrightsp);
3148 if (__predict_false(error != 0))
3155 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3160 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3162 if (__predict_false(fd >= fdp->fd_nfiles))
3165 fp = fdp->fd_ofiles[fd].fde_file;
3166 if (__predict_false(fp == NULL))
3169 MPASS(refcount_load(&fp->f_count) > 0);
3176 * Extract the file pointer associated with the specified descriptor for the
3177 * current user process.
3179 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3182 * File's rights will be checked against the capability rights mask.
3184 * If an error occurred the non-zero error is returned and *fpp is set to
3185 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
3186 * responsible for fdrop().
3189 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3190 cap_rights_t *needrightsp)
3192 struct filedesc *fdp;
3197 fdp = td->td_proc->p_fd;
3198 error = fget_unlocked(fdp, fd, needrightsp, &fp);
3199 if (__predict_false(error != 0))
3201 if (__predict_false(fp->f_ops == &badfileops)) {
3207 * FREAD and FWRITE failure return EBADF as per POSIX.
3213 if ((fp->f_flag & flags) == 0)
3217 if (fp->f_ops != &path_fileops &&
3218 ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3219 (fp->f_flag & FWRITE) != 0))
3225 KASSERT(0, ("wrong flags"));
3238 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3241 return (_fget(td, fd, fpp, 0, rightsp));
3245 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
3249 #ifndef CAPABILITIES
3250 error = _fget(td, fd, fpp, 0, rightsp);
3251 if (maxprotp != NULL)
3252 *maxprotp = VM_PROT_ALL;
3255 cap_rights_t fdrights;
3256 struct filedesc *fdp;
3261 fdp = td->td_proc->p_fd;
3262 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3264 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
3265 if (__predict_false(error != 0))
3267 if (__predict_false(fp->f_ops == &badfileops)) {
3271 if (maxprotp != NULL)
3272 fdrights = *cap_rights(fdp, fd);
3273 if (!fd_modified(fdp, fd, seq))
3279 * If requested, convert capability rights to access flags.
3281 if (maxprotp != NULL)
3282 *maxprotp = cap_rights_to_vmprot(&fdrights);
3289 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3292 return (_fget(td, fd, fpp, FREAD, rightsp));
3296 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3299 return (_fget(td, fd, fpp, FWRITE, rightsp));
3303 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
3306 struct filedesc *fdp = td->td_proc->p_fd;
3307 #ifndef CAPABILITIES
3308 return (fget_unlocked(fdp, fd, rightsp, fpp));
3315 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3317 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
3320 error = cap_fcntl_check(fdp, fd, needfcntl);
3321 if (!fd_modified(fdp, fd, seq))
3335 * Like fget() but loads the underlying vnode, or returns an error if the
3336 * descriptor does not represent a vnode. Note that pipes use vnodes but
3337 * never have VM objects. The returned vnode will be vref()'d.
3339 * XXX: what about the unused flags ?
3342 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3349 error = _fget(td, fd, &fp, flags, needrightsp);
3352 if (fp->f_vnode == NULL) {
3364 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3367 return (_fgetvp(td, fd, 0, rightsp, vpp));
3371 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3372 struct filecaps *havecaps, struct vnode **vpp)
3374 struct filecaps caps;
3378 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3381 if (fp->f_ops == &badfileops) {
3385 if (fp->f_vnode == NULL) {
3397 filecaps_free(&caps);
3403 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3406 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3410 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3413 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3418 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3422 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3427 * Handle the last reference to a file being closed.
3429 * Without the noinline attribute clang keeps inlining the func thorough this
3430 * file when fdrop is used.
3433 _fdrop(struct file *fp, struct thread *td)
3439 count = refcount_load(&fp->f_count);
3441 panic("fdrop: fp %p count %d", fp, count);
3443 error = fo_close(fp, td);
3444 atomic_subtract_int(&openfiles, 1);
3446 free(fp->f_advice, M_FADVISE);
3447 uma_zfree(file_zone, fp);
3453 * Apply an advisory lock on a file descriptor.
3455 * Just attempt to get a record lock of the requested type on the entire file
3456 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3458 #ifndef _SYS_SYSPROTO_H_
3466 sys_flock(struct thread *td, struct flock_args *uap)
3473 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3477 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3480 if (fp->f_ops == &path_fileops) {
3486 lf.l_whence = SEEK_SET;
3489 if (uap->how & LOCK_UN) {
3490 lf.l_type = F_UNLCK;
3491 atomic_clear_int(&fp->f_flag, FHASLOCK);
3492 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3495 if (uap->how & LOCK_EX)
3496 lf.l_type = F_WRLCK;
3497 else if (uap->how & LOCK_SH)
3498 lf.l_type = F_RDLCK;
3503 atomic_set_int(&fp->f_flag, FHASLOCK);
3504 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3505 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3511 * Duplicate the specified descriptor to a free descriptor.
3514 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3515 int openerror, int *indxp)
3517 struct filedescent *newfde, *oldfde;
3522 KASSERT(openerror == ENODEV || openerror == ENXIO,
3523 ("unexpected error %d in %s", openerror, __func__));
3526 * If the to-be-dup'd fd number is greater than the allowed number
3527 * of file descriptors, or the fd to be dup'd has already been
3528 * closed, then reject.
3530 FILEDESC_XLOCK(fdp);
3531 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3532 FILEDESC_XUNLOCK(fdp);
3536 error = fdalloc(td, 0, &indx);
3538 FILEDESC_XUNLOCK(fdp);
3543 * There are two cases of interest here.
3545 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3547 * For ENXIO steal away the file structure from (dfd) and store it in
3548 * (indx). (dfd) is effectively closed by this operation.
3550 switch (openerror) {
3553 * Check that the mode the file is being opened for is a
3554 * subset of the mode of the existing descriptor.
3556 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3557 fdunused(fdp, indx);
3558 FILEDESC_XUNLOCK(fdp);
3562 fdunused(fdp, indx);
3563 FILEDESC_XUNLOCK(fdp);
3566 newfde = &fdp->fd_ofiles[indx];
3567 oldfde = &fdp->fd_ofiles[dfd];
3568 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3570 seqc_write_begin(&newfde->fde_seqc);
3572 memcpy(newfde, oldfde, fde_change_size);
3573 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3576 seqc_write_end(&newfde->fde_seqc);
3581 * Steal away the file pointer from dfd and stuff it into indx.
3583 newfde = &fdp->fd_ofiles[indx];
3584 oldfde = &fdp->fd_ofiles[dfd];
3586 seqc_write_begin(&newfde->fde_seqc);
3588 memcpy(newfde, oldfde, fde_change_size);
3589 oldfde->fde_file = NULL;
3592 seqc_write_end(&newfde->fde_seqc);
3596 FILEDESC_XUNLOCK(fdp);
3602 * This sysctl determines if we will allow a process to chroot(2) if it
3603 * has a directory open:
3604 * 0: disallowed for all processes.
3605 * 1: allowed for processes that were not already chroot(2)'ed.
3606 * 2: allowed for all processes.
3609 static int chroot_allow_open_directories = 1;
3611 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3612 &chroot_allow_open_directories, 0,
3613 "Allow a process to chroot(2) if it has a directory open");
3616 * Helper function for raised chroot(2) security function: Refuse if
3617 * any filedescriptors are open directories.
3620 chroot_refuse_vdir_fds(struct filedesc *fdp)
3626 FILEDESC_LOCK_ASSERT(fdp);
3628 lastfile = fdlastfile(fdp);
3629 for (fd = 0; fd <= lastfile; fd++) {
3630 fp = fget_locked(fdp, fd);
3633 if (fp->f_type == DTYPE_VNODE) {
3635 if (vp->v_type == VDIR)
3643 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3646 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3647 vrefact(oldpwd->pwd_cdir);
3648 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3651 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3652 vrefact(oldpwd->pwd_rdir);
3653 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3656 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3657 vrefact(oldpwd->pwd_jdir);
3658 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3663 pwd_hold_pwddesc(struct pwddesc *pdp)
3667 PWDDESC_ASSERT_XLOCKED(pdp);
3668 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3670 refcount_acquire(&pwd->pwd_refcount);
3675 pwd_hold_smr(struct pwd *pwd)
3679 if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3686 pwd_hold(struct thread *td)
3688 struct pwddesc *pdp;
3691 pdp = td->td_proc->p_pd;
3694 pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3695 if (pwd_hold_smr(pwd)) {
3701 pwd = pwd_hold_pwddesc(pdp);
3703 PWDDESC_XUNLOCK(pdp);
3708 pwd_hold_proc(struct proc *p)
3710 struct pwddesc *pdp;
3713 PROC_ASSERT_HELD(p);
3720 pwd = pwd_hold_pwddesc(pdp);
3722 PWDDESC_XUNLOCK(pdp);
3732 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3733 bzero(pwd, sizeof(*pwd));
3734 refcount_init(&pwd->pwd_refcount, 1);
3739 pwd_drop(struct pwd *pwd)
3742 if (!refcount_release(&pwd->pwd_refcount))
3745 if (pwd->pwd_cdir != NULL)
3746 vrele(pwd->pwd_cdir);
3747 if (pwd->pwd_rdir != NULL)
3748 vrele(pwd->pwd_rdir);
3749 if (pwd->pwd_jdir != NULL)
3750 vrele(pwd->pwd_jdir);
3751 uma_zfree_smr(pwd_zone, pwd);
3755 * The caller is responsible for invoking priv_check() and
3756 * mac_vnode_check_chroot() to authorize this operation.
3759 pwd_chroot(struct thread *td, struct vnode *vp)
3761 struct pwddesc *pdp;
3762 struct filedesc *fdp;
3763 struct pwd *newpwd, *oldpwd;
3766 fdp = td->td_proc->p_fd;
3767 pdp = td->td_proc->p_pd;
3768 newpwd = pwd_alloc();
3769 FILEDESC_SLOCK(fdp);
3771 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3772 if (chroot_allow_open_directories == 0 ||
3773 (chroot_allow_open_directories == 1 &&
3774 oldpwd->pwd_rdir != rootvnode)) {
3775 error = chroot_refuse_vdir_fds(fdp);
3776 FILEDESC_SUNLOCK(fdp);
3778 PWDDESC_XUNLOCK(pdp);
3783 FILEDESC_SUNLOCK(fdp);
3787 newpwd->pwd_rdir = vp;
3788 if (oldpwd->pwd_jdir == NULL) {
3790 newpwd->pwd_jdir = vp;
3792 pwd_fill(oldpwd, newpwd);
3793 pwd_set(pdp, newpwd);
3794 PWDDESC_XUNLOCK(pdp);
3800 pwd_chdir(struct thread *td, struct vnode *vp)
3802 struct pwddesc *pdp;
3803 struct pwd *newpwd, *oldpwd;
3805 VNPASS(vp->v_usecount > 0, vp);
3807 newpwd = pwd_alloc();
3808 pdp = td->td_proc->p_pd;
3810 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3811 newpwd->pwd_cdir = vp;
3812 pwd_fill(oldpwd, newpwd);
3813 pwd_set(pdp, newpwd);
3814 PWDDESC_XUNLOCK(pdp);
3819 * jail_attach(2) changes both root and working directories.
3822 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
3824 struct pwddesc *pdp;
3825 struct filedesc *fdp;
3826 struct pwd *newpwd, *oldpwd;
3829 fdp = td->td_proc->p_fd;
3830 pdp = td->td_proc->p_pd;
3831 newpwd = pwd_alloc();
3832 FILEDESC_SLOCK(fdp);
3834 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3835 error = chroot_refuse_vdir_fds(fdp);
3836 FILEDESC_SUNLOCK(fdp);
3838 PWDDESC_XUNLOCK(pdp);
3844 newpwd->pwd_rdir = vp;
3846 newpwd->pwd_cdir = vp;
3847 if (oldpwd->pwd_jdir == NULL) {
3849 newpwd->pwd_jdir = vp;
3851 pwd_fill(oldpwd, newpwd);
3852 pwd_set(pdp, newpwd);
3853 PWDDESC_XUNLOCK(pdp);
3859 pwd_ensure_dirs(void)
3861 struct pwddesc *pdp;
3862 struct pwd *oldpwd, *newpwd;
3864 pdp = curproc->p_pd;
3866 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3867 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3868 PWDDESC_XUNLOCK(pdp);
3871 PWDDESC_XUNLOCK(pdp);
3873 newpwd = pwd_alloc();
3875 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3876 pwd_fill(oldpwd, newpwd);
3877 if (newpwd->pwd_cdir == NULL) {
3879 newpwd->pwd_cdir = rootvnode;
3881 if (newpwd->pwd_rdir == NULL) {
3883 newpwd->pwd_rdir = rootvnode;
3885 pwd_set(pdp, newpwd);
3886 PWDDESC_XUNLOCK(pdp);
3891 pwd_set_rootvnode(void)
3893 struct pwddesc *pdp;
3894 struct pwd *oldpwd, *newpwd;
3896 pdp = curproc->p_pd;
3898 newpwd = pwd_alloc();
3900 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3902 newpwd->pwd_cdir = rootvnode;
3904 newpwd->pwd_rdir = rootvnode;
3905 pwd_fill(oldpwd, newpwd);
3906 pwd_set(pdp, newpwd);
3907 PWDDESC_XUNLOCK(pdp);
3912 * Scan all active processes and prisons to see if any of them have a current
3913 * or root directory of `olddp'. If so, replace them with the new mount point.
3916 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3918 struct pwddesc *pdp;
3919 struct pwd *newpwd, *oldpwd;
3924 if (vrefcnt(olddp) == 1)
3927 newpwd = pwd_alloc();
3928 sx_slock(&allproc_lock);
3929 FOREACH_PROC_IN_SYSTEM(p) {
3936 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3937 if (oldpwd == NULL ||
3938 (oldpwd->pwd_cdir != olddp &&
3939 oldpwd->pwd_rdir != olddp &&
3940 oldpwd->pwd_jdir != olddp)) {
3941 PWDDESC_XUNLOCK(pdp);
3945 if (oldpwd->pwd_cdir == olddp) {
3947 newpwd->pwd_cdir = newdp;
3949 if (oldpwd->pwd_rdir == olddp) {
3951 newpwd->pwd_rdir = newdp;
3953 if (oldpwd->pwd_jdir == olddp) {
3955 newpwd->pwd_jdir = newdp;
3957 pwd_fill(oldpwd, newpwd);
3958 pwd_set(pdp, newpwd);
3959 PWDDESC_XUNLOCK(pdp);
3962 newpwd = pwd_alloc();
3964 sx_sunlock(&allproc_lock);
3966 if (rootvnode == olddp) {
3971 mtx_lock(&prison0.pr_mtx);
3972 if (prison0.pr_root == olddp) {
3974 prison0.pr_root = newdp;
3977 mtx_unlock(&prison0.pr_mtx);
3978 sx_slock(&allprison_lock);
3979 TAILQ_FOREACH(pr, &allprison, pr_list) {
3980 mtx_lock(&pr->pr_mtx);
3981 if (pr->pr_root == olddp) {
3983 pr->pr_root = newdp;
3986 mtx_unlock(&pr->pr_mtx);
3988 sx_sunlock(&allprison_lock);
3993 struct filedesc_to_leader *
3994 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3996 struct filedesc_to_leader *fdtol;
3998 fdtol = malloc(sizeof(struct filedesc_to_leader),
3999 M_FILEDESC_TO_LEADER, M_WAITOK);
4000 fdtol->fdl_refcount = 1;
4001 fdtol->fdl_holdcount = 0;
4002 fdtol->fdl_wakeup = 0;
4003 fdtol->fdl_leader = leader;
4005 FILEDESC_XLOCK(fdp);
4006 fdtol->fdl_next = old->fdl_next;
4007 fdtol->fdl_prev = old;
4008 old->fdl_next = fdtol;
4009 fdtol->fdl_next->fdl_prev = fdtol;
4010 FILEDESC_XUNLOCK(fdp);
4012 fdtol->fdl_next = fdtol;
4013 fdtol->fdl_prev = fdtol;
4019 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4022 struct filedesc *fdp;
4024 int count, off, minoff;
4030 if (*(int *)arg1 != 0)
4033 fdp = curproc->p_fd;
4035 FILEDESC_SLOCK(fdp);
4037 off = NDSLOT(fdp->fd_nfiles - 1);
4038 for (minoff = NDSLOT(0); off >= minoff; --off)
4039 count += bitcountl(map[off]);
4040 FILEDESC_SUNLOCK(fdp);
4042 return (SYSCTL_OUT(req, &count, sizeof(count)));
4045 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4046 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4047 "Number of open file descriptors");
4050 * Get file structures globally.
4053 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4056 struct filedesc *fdp;
4059 int error, n, lastfile;
4061 error = sysctl_wire_old_buffer(req, 0);
4064 if (req->oldptr == NULL) {
4066 sx_slock(&allproc_lock);
4067 FOREACH_PROC_IN_SYSTEM(p) {
4069 if (p->p_state == PRS_NEW) {
4077 /* overestimates sparse tables. */
4078 n += fdp->fd_nfiles;
4081 sx_sunlock(&allproc_lock);
4082 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4085 bzero(&xf, sizeof(xf));
4086 xf.xf_size = sizeof(xf);
4087 sx_slock(&allproc_lock);
4088 FOREACH_PROC_IN_SYSTEM(p) {
4090 if (p->p_state == PRS_NEW) {
4094 if (p_cansee(req->td, p) != 0) {
4098 xf.xf_pid = p->p_pid;
4099 xf.xf_uid = p->p_ucred->cr_uid;
4104 FILEDESC_SLOCK(fdp);
4105 lastfile = fdlastfile(fdp);
4106 for (n = 0; refcount_load(&fdp->fd_refcnt) > 0 && n <= lastfile;
4108 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4111 xf.xf_file = (uintptr_t)fp;
4112 xf.xf_data = (uintptr_t)fp->f_data;
4113 xf.xf_vnode = (uintptr_t)fp->f_vnode;
4114 xf.xf_type = (uintptr_t)fp->f_type;
4115 xf.xf_count = refcount_load(&fp->f_count);
4117 xf.xf_offset = foffset_get(fp);
4118 xf.xf_flag = fp->f_flag;
4119 error = SYSCTL_OUT(req, &xf, sizeof(xf));
4123 FILEDESC_SUNLOCK(fdp);
4128 sx_sunlock(&allproc_lock);
4132 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4133 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4135 #ifdef KINFO_FILE_SIZE
4136 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4140 xlate_fflags(int fflags)
4142 static const struct {
4145 } fflags_table[] = {
4146 { FAPPEND, KF_FLAG_APPEND },
4147 { FASYNC, KF_FLAG_ASYNC },
4148 { FFSYNC, KF_FLAG_FSYNC },
4149 { FHASLOCK, KF_FLAG_HASLOCK },
4150 { FNONBLOCK, KF_FLAG_NONBLOCK },
4151 { FREAD, KF_FLAG_READ },
4152 { FWRITE, KF_FLAG_WRITE },
4153 { O_CREAT, KF_FLAG_CREAT },
4154 { O_DIRECT, KF_FLAG_DIRECT },
4155 { O_EXCL, KF_FLAG_EXCL },
4156 { O_EXEC, KF_FLAG_EXEC },
4157 { O_EXLOCK, KF_FLAG_EXLOCK },
4158 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4159 { O_SHLOCK, KF_FLAG_SHLOCK },
4160 { O_TRUNC, KF_FLAG_TRUNC }
4166 for (i = 0; i < nitems(fflags_table); i++)
4167 if (fflags & fflags_table[i].fflag)
4168 kflags |= fflags_table[i].kf_fflag;
4172 /* Trim unused data from kf_path by truncating the structure size. */
4174 pack_kinfo(struct kinfo_file *kif)
4177 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4178 strlen(kif->kf_path) + 1;
4179 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4183 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4184 struct kinfo_file *kif, struct filedesc *fdp, int flags)
4188 bzero(kif, sizeof(*kif));
4190 /* Set a default type to allow for empty fill_kinfo() methods. */
4191 kif->kf_type = KF_TYPE_UNKNOWN;
4192 kif->kf_flags = xlate_fflags(fp->f_flag);
4193 if (rightsp != NULL)
4194 kif->kf_cap_rights = *rightsp;
4196 cap_rights_init_zero(&kif->kf_cap_rights);
4198 kif->kf_ref_count = refcount_load(&fp->f_count);
4199 kif->kf_offset = foffset_get(fp);
4202 * This may drop the filedesc lock, so the 'fp' cannot be
4203 * accessed after this call.
4205 error = fo_fill_kinfo(fp, kif, fdp);
4207 kif->kf_status |= KF_ATTR_VALID;
4208 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4211 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4215 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4216 struct kinfo_file *kif, int flags)
4220 bzero(kif, sizeof(*kif));
4222 kif->kf_type = KF_TYPE_VNODE;
4223 error = vn_fill_kinfo_vnode(vp, kif);
4225 kif->kf_status |= KF_ATTR_VALID;
4226 kif->kf_flags = xlate_fflags(fflags);
4227 cap_rights_init_zero(&kif->kf_cap_rights);
4229 kif->kf_ref_count = -1;
4230 kif->kf_offset = -1;
4231 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4234 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4238 struct export_fd_buf {
4239 struct filedesc *fdp;
4240 struct pwddesc *pdp;
4243 struct kinfo_file kif;
4248 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4250 struct kinfo_file *kif;
4253 if (efbuf->remainder != -1) {
4254 if (efbuf->remainder < kif->kf_structsize) {
4255 /* Terminate export. */
4256 efbuf->remainder = 0;
4259 efbuf->remainder -= kif->kf_structsize;
4261 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
4265 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4266 struct export_fd_buf *efbuf)
4270 if (efbuf->remainder == 0)
4272 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4274 FILEDESC_SUNLOCK(efbuf->fdp);
4275 error = export_kinfo_to_sb(efbuf);
4276 FILEDESC_SLOCK(efbuf->fdp);
4281 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4282 struct export_fd_buf *efbuf)
4286 if (efbuf->remainder == 0)
4288 if (efbuf->pdp != NULL)
4289 PWDDESC_XUNLOCK(efbuf->pdp);
4290 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4291 error = export_kinfo_to_sb(efbuf);
4292 if (efbuf->pdp != NULL)
4293 PWDDESC_XLOCK(efbuf->pdp);
4298 * Store a process file descriptor information to sbuf.
4300 * Takes a locked proc as argument, and returns with the proc unlocked.
4303 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
4307 struct filedesc *fdp;
4308 struct pwddesc *pdp;
4309 struct export_fd_buf *efbuf;
4310 struct vnode *cttyvp, *textvp, *tracevp;
4312 int error, i, lastfile;
4313 cap_rights_t rights;
4315 PROC_LOCK_ASSERT(p, MA_OWNED);
4318 tracevp = ktr_get_tracevp(p, true);
4320 textvp = p->p_textvp;
4323 /* Controlling tty. */
4325 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4326 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4333 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4337 efbuf->remainder = maxlen;
4338 efbuf->flags = flags;
4339 if (tracevp != NULL)
4340 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
4343 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
4345 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
4348 if (pdp == NULL || fdp == NULL)
4353 pwd = pwd_hold_pwddesc(pdp);
4355 /* working directory */
4356 if (pwd->pwd_cdir != NULL) {
4357 vrefact(pwd->pwd_cdir);
4358 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD,
4361 /* root directory */
4362 if (pwd->pwd_rdir != NULL) {
4363 vrefact(pwd->pwd_rdir);
4364 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT,
4367 /* jail directory */
4368 if (pwd->pwd_jdir != NULL) {
4369 vrefact(pwd->pwd_jdir);
4370 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL,
4374 PWDDESC_XUNLOCK(pdp);
4377 FILEDESC_SLOCK(fdp);
4378 lastfile = fdlastfile(fdp);
4379 for (i = 0; refcount_load(&fdp->fd_refcnt) > 0 && i <= lastfile; i++) {
4380 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4383 rights = *cap_rights(fdp, i);
4384 #else /* !CAPABILITIES */
4385 rights = cap_no_rights;
4388 * Create sysctl entry. It is OK to drop the filedesc
4389 * lock inside of export_file_to_sb() as we will
4390 * re-validate and re-evaluate its properties when the
4393 error = export_file_to_sb(fp, i, &rights, efbuf);
4394 if (error != 0 || efbuf->remainder == 0)
4397 FILEDESC_SUNLOCK(fdp);
4403 free(efbuf, M_TEMP);
4407 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
4410 * Get per-process file descriptors for use by procstat(1), et al.
4413 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4419 int error, error2, *name;
4427 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4428 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4429 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4434 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4435 error = kern_proc_filedesc_out(p, &sb, maxlen,
4436 KERN_FILEDESC_PACK_KINFO);
4437 error2 = sbuf_finish(&sb);
4439 return (error != 0 ? error : error2);
4442 #ifdef COMPAT_FREEBSD7
4443 #ifdef KINFO_OFILE_SIZE
4444 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4448 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4451 okif->kf_structsize = sizeof(*okif);
4452 okif->kf_type = kif->kf_type;
4453 okif->kf_fd = kif->kf_fd;
4454 okif->kf_ref_count = kif->kf_ref_count;
4455 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4456 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4457 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4458 okif->kf_offset = kif->kf_offset;
4459 if (kif->kf_type == KF_TYPE_VNODE)
4460 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4462 okif->kf_vnode_type = KF_VTYPE_VNON;
4463 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4464 if (kif->kf_type == KF_TYPE_SOCKET) {
4465 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4466 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4467 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4468 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4469 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4471 okif->kf_sa_local.ss_family = AF_UNSPEC;
4472 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4477 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4478 struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4483 PWDDESC_XUNLOCK(pdp);
4484 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4485 kinfo_to_okinfo(kif, okif);
4486 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4492 * Get per-process file descriptors for use by procstat(1), et al.
4495 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4497 struct kinfo_ofile *okif;
4498 struct kinfo_file *kif;
4499 struct filedesc *fdp;
4500 struct pwddesc *pdp;
4503 int error, i, lastfile, *name;
4512 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4519 if (fdp == NULL || pdp == NULL) {
4524 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4525 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4527 pwd = pwd_hold_pwddesc(pdp);
4529 if (pwd->pwd_cdir != NULL)
4530 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4532 if (pwd->pwd_rdir != NULL)
4533 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4535 if (pwd->pwd_jdir != NULL)
4536 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4539 PWDDESC_XUNLOCK(pdp);
4542 FILEDESC_SLOCK(fdp);
4543 lastfile = fdlastfile(fdp);
4544 for (i = 0; refcount_load(&fdp->fd_refcnt) > 0 && i <= lastfile; i++) {
4545 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4547 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4548 KERN_FILEDESC_PACK_KINFO);
4549 FILEDESC_SUNLOCK(fdp);
4550 kinfo_to_okinfo(kif, okif);
4551 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4552 FILEDESC_SLOCK(fdp);
4556 FILEDESC_SUNLOCK(fdp);
4564 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4565 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4566 "Process ofiledesc entries");
4567 #endif /* COMPAT_FREEBSD7 */
4570 vntype_to_kinfo(int vtype)
4575 } vtypes_table[] = {
4576 { VBAD, KF_VTYPE_VBAD },
4577 { VBLK, KF_VTYPE_VBLK },
4578 { VCHR, KF_VTYPE_VCHR },
4579 { VDIR, KF_VTYPE_VDIR },
4580 { VFIFO, KF_VTYPE_VFIFO },
4581 { VLNK, KF_VTYPE_VLNK },
4582 { VNON, KF_VTYPE_VNON },
4583 { VREG, KF_VTYPE_VREG },
4584 { VSOCK, KF_VTYPE_VSOCK }
4589 * Perform vtype translation.
4591 for (i = 0; i < nitems(vtypes_table); i++)
4592 if (vtypes_table[i].vtype == vtype)
4593 return (vtypes_table[i].kf_vtype);
4595 return (KF_VTYPE_UNKNOWN);
4598 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4599 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4600 "Process filedesc entries");
4603 * Store a process current working directory information to sbuf.
4605 * Takes a locked proc as argument, and returns with the proc unlocked.
4608 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4610 struct pwddesc *pdp;
4612 struct export_fd_buf *efbuf;
4616 PROC_LOCK_ASSERT(p, MA_OWNED);
4623 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4626 efbuf->remainder = maxlen;
4629 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4630 cdir = pwd->pwd_cdir;
4635 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4637 PWDDESC_XUNLOCK(pdp);
4639 free(efbuf, M_TEMP);
4644 * Get per-process current working directory.
4647 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4653 int error, error2, *name;
4661 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4662 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4663 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4668 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4669 error = kern_proc_cwd_out(p, &sb, maxlen);
4670 error2 = sbuf_finish(&sb);
4672 return (error != 0 ? error : error2);
4675 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4676 sysctl_kern_proc_cwd, "Process current working directory");
4680 * For the purposes of debugging, generate a human-readable string for the
4684 file_type_to_name(short type)
4712 case DTYPE_PROCDESC:
4716 case DTYPE_LINUXTFD:
4724 * For the purposes of debugging, identify a process (if any, perhaps one of
4725 * many) that references the passed file in its file descriptor array. Return
4728 static struct proc *
4729 file_to_first_proc(struct file *fp)
4731 struct filedesc *fdp;
4735 FOREACH_PROC_IN_SYSTEM(p) {
4736 if (p->p_state == PRS_NEW)
4741 for (n = 0; n < fdp->fd_nfiles; n++) {
4742 if (fp == fdp->fd_ofiles[n].fde_file)
4750 db_print_file(struct file *fp, int header)
4752 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4756 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4757 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4758 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4760 p = file_to_first_proc(fp);
4761 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4762 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4763 fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
4764 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4769 DB_SHOW_COMMAND(file, db_show_file)
4774 db_printf("usage: show file <addr>\n");
4777 fp = (struct file *)addr;
4778 db_print_file(fp, 1);
4781 DB_SHOW_COMMAND(files, db_show_files)
4783 struct filedesc *fdp;
4790 FOREACH_PROC_IN_SYSTEM(p) {
4791 if (p->p_state == PRS_NEW)
4793 if ((fdp = p->p_fd) == NULL)
4795 for (n = 0; n < fdp->fd_nfiles; ++n) {
4796 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4798 db_print_file(fp, header);
4805 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4806 &maxfilesperproc, 0, "Maximum files allowed open per process");
4808 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4809 &maxfiles, 0, "Maximum number of files");
4811 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4812 &openfiles, 0, "System-wide number of open files");
4816 filelistinit(void *dummy)
4819 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4820 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4821 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4822 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4823 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4824 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4826 * XXXMJG this is a temporary hack due to boot ordering issues against
4829 vfs_smr = uma_zone_get_smr(pwd_zone);
4830 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4832 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4834 /*-------------------------------------------------------------------*/
4837 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4838 int flags, struct thread *td)
4845 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4853 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4861 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4869 badfo_kqfilter(struct file *fp, struct knote *kn)
4876 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
4883 badfo_close(struct file *fp, struct thread *td)
4890 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4898 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4906 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4907 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4915 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4921 struct fileops badfileops = {
4922 .fo_read = badfo_readwrite,
4923 .fo_write = badfo_readwrite,
4924 .fo_truncate = badfo_truncate,
4925 .fo_ioctl = badfo_ioctl,
4926 .fo_poll = badfo_poll,
4927 .fo_kqfilter = badfo_kqfilter,
4928 .fo_stat = badfo_stat,
4929 .fo_close = badfo_close,
4930 .fo_chmod = badfo_chmod,
4931 .fo_chown = badfo_chown,
4932 .fo_sendfile = badfo_sendfile,
4933 .fo_fill_kinfo = badfo_fill_kinfo,
4937 path_poll(struct file *fp, int events, struct ucred *active_cred,
4944 path_close(struct file *fp, struct thread *td)
4946 MPASS(fp->f_type == DTYPE_VNODE);
4947 fp->f_ops = &badfileops;
4952 struct fileops path_fileops = {
4953 .fo_read = badfo_readwrite,
4954 .fo_write = badfo_readwrite,
4955 .fo_truncate = badfo_truncate,
4956 .fo_ioctl = badfo_ioctl,
4957 .fo_poll = path_poll,
4958 .fo_kqfilter = vn_kqfilter_opath,
4959 .fo_stat = vn_statfile,
4960 .fo_close = path_close,
4961 .fo_chmod = badfo_chmod,
4962 .fo_chown = badfo_chown,
4963 .fo_sendfile = badfo_sendfile,
4964 .fo_fill_kinfo = vn_fill_kinfo,
4965 .fo_flags = DFLAG_PASSABLE,
4969 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4970 int flags, struct thread *td)
4973 return (EOPNOTSUPP);
4977 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4985 invfo_ioctl(struct file *fp, u_long com, void *data,
4986 struct ucred *active_cred, struct thread *td)
4993 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4997 return (poll_no_poll(events));
5001 invfo_kqfilter(struct file *fp, struct knote *kn)
5008 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5016 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5024 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5025 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5032 /*-------------------------------------------------------------------*/
5035 * File Descriptor pseudo-device driver (/dev/fd/).
5037 * Opening minor device N dup()s the file (if any) connected to file
5038 * descriptor N belonging to the calling process. Note that this driver
5039 * consists of only the ``open()'' routine, because all subsequent
5040 * references to this file will be direct to the other driver.
5042 * XXX: we could give this one a cloning event handler if necessary.
5047 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5051 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5052 * the file descriptor being sought for duplication. The error
5053 * return ensures that the vnode for this device will be released
5054 * by vn_open. Open will detect this special error and take the
5055 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5056 * will simply report the error.
5058 td->td_dupfd = dev2unit(dev);
5062 static struct cdevsw fildesc_cdevsw = {
5063 .d_version = D_VERSION,
5069 fildesc_drvinit(void *unused)
5073 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5074 UID_ROOT, GID_WHEEL, 0666, "fd/0");
5075 make_dev_alias(dev, "stdin");
5076 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5077 UID_ROOT, GID_WHEEL, 0666, "fd/1");
5078 make_dev_alias(dev, "stdout");
5079 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5080 UID_ROOT, GID_WHEEL, 0666, "fd/2");
5081 make_dev_alias(dev, "stderr");
5084 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);