2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
44 #include "opt_ktrace.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capsicum.h>
51 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
56 #include <sys/kernel.h>
57 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/selinfo.h>
66 #include <sys/protosw.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
70 #include <sys/signalvar.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysproto.h>
78 #include <sys/unistd.h>
80 #include <sys/vnode.h>
82 #include <sys/ktrace.h>
87 #include <security/audit/audit.h>
94 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
95 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
96 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
97 "file desc to leader structures");
98 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
99 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
101 MALLOC_DECLARE(M_FADVISE);
103 static __read_mostly uma_zone_t file_zone;
104 static __read_mostly uma_zone_t filedesc0_zone;
105 __read_mostly uma_zone_t pwd_zone;
108 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
109 struct thread *td, int holdleaders);
110 static int fd_first_free(struct filedesc *fdp, int low, int size);
111 static 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 fde = &fdp->fd_ofiles[fd];
311 seqc_write_begin(&fde->fde_seqc);
313 fde->fde_file = NULL;
315 seqc_write_end(&fde->fde_seqc);
322 * System calls on descriptors.
324 #ifndef _SYS_SYSPROTO_H_
325 struct getdtablesize_args {
331 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
337 td->td_retval[0] = getmaxfd(td);
339 PROC_LOCK(td->td_proc);
340 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
341 PROC_UNLOCK(td->td_proc);
342 if (lim < td->td_retval[0])
343 td->td_retval[0] = lim;
349 * Duplicate a file descriptor to a particular value.
351 * Note: keep in mind that a potential race condition exists when closing
352 * descriptors from a shared descriptor table (via rfork).
354 #ifndef _SYS_SYSPROTO_H_
362 sys_dup2(struct thread *td, struct dup2_args *uap)
365 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
369 * Duplicate a file descriptor.
371 #ifndef _SYS_SYSPROTO_H_
378 sys_dup(struct thread *td, struct dup_args *uap)
381 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
385 * The file control system call.
387 #ifndef _SYS_SYSPROTO_H_
396 sys_fcntl(struct thread *td, struct fcntl_args *uap)
399 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
403 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
417 * Convert old flock structure to new.
419 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
420 fl.l_start = ofl.l_start;
421 fl.l_len = ofl.l_len;
422 fl.l_pid = ofl.l_pid;
423 fl.l_type = ofl.l_type;
424 fl.l_whence = ofl.l_whence;
438 arg1 = (intptr_t)&fl;
444 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
445 arg1 = (intptr_t)&fl;
453 error = kern_fcntl(td, fd, newcmd, arg1);
456 if (cmd == F_OGETLK) {
457 ofl.l_start = fl.l_start;
458 ofl.l_len = fl.l_len;
459 ofl.l_pid = fl.l_pid;
460 ofl.l_type = fl.l_type;
461 ofl.l_whence = fl.l_whence;
462 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
463 } else if (cmd == F_GETLK) {
464 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
470 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
472 struct filedesc *fdp;
474 struct file *fp, *fp2;
475 struct filedescent *fde;
479 int error, flg, seals, tmp;
493 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
496 case F_DUPFD_CLOEXEC:
498 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
503 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
506 case F_DUP2FD_CLOEXEC:
508 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
514 fde = fdeget_locked(fdp, fd);
517 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
520 FILEDESC_SUNLOCK(fdp);
526 fde = fdeget_locked(fdp, fd);
528 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
529 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
532 FILEDESC_XUNLOCK(fdp);
536 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
539 td->td_retval[0] = OFLAGS(fp->f_flag);
544 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
548 tmp = flg = fp->f_flag;
550 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
551 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
552 tmp = fp->f_flag & FNONBLOCK;
553 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
558 tmp = fp->f_flag & FASYNC;
559 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
564 atomic_clear_int(&fp->f_flag, FNONBLOCK);
566 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
571 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
574 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
576 td->td_retval[0] = tmp;
581 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
585 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
590 error = priv_check(td, PRIV_NFS_LOCKD);
598 /* FALLTHROUGH F_SETLK */
602 flp = (struct flock *)arg;
603 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
608 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
611 if (fp->f_type != DTYPE_VNODE) {
617 if (flp->l_whence == SEEK_CUR) {
618 foffset = foffset_get(fp);
621 foffset > OFF_MAX - flp->l_start)) {
626 flp->l_start += foffset;
630 switch (flp->l_type) {
632 if ((fp->f_flag & FREAD) == 0) {
636 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
637 PROC_LOCK(p->p_leader);
638 p->p_leader->p_flag |= P_ADVLOCK;
639 PROC_UNLOCK(p->p_leader);
641 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
645 if ((fp->f_flag & FWRITE) == 0) {
649 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
650 PROC_LOCK(p->p_leader);
651 p->p_leader->p_flag |= P_ADVLOCK;
652 PROC_UNLOCK(p->p_leader);
654 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
658 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
662 if (flg != F_REMOTE) {
666 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
667 F_UNLCKSYS, flp, flg);
673 if (error != 0 || flp->l_type == F_UNLCK ||
674 flp->l_type == F_UNLCKSYS) {
680 * Check for a race with close.
682 * The vnode is now advisory locked (or unlocked, but this case
683 * is not really important) as the caller requested.
684 * We had to drop the filedesc lock, so we need to recheck if
685 * the descriptor is still valid, because if it was closed
686 * in the meantime we need to remove advisory lock from the
687 * vnode - close on any descriptor leading to an advisory
688 * locked vnode, removes that lock.
689 * We will return 0 on purpose in that case, as the result of
690 * successful advisory lock might have been externally visible
691 * already. This is fine - effectively we pretend to the caller
692 * that the closing thread was a bit slower and that the
693 * advisory lock succeeded before the close.
695 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
701 flp->l_whence = SEEK_SET;
704 flp->l_type = F_UNLCK;
705 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
706 F_UNLCK, flp, F_POSIX);
713 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
716 if (fp->f_type != DTYPE_VNODE) {
721 flp = (struct flock *)arg;
722 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
723 flp->l_type != F_UNLCK) {
728 if (flp->l_whence == SEEK_CUR) {
729 foffset = foffset_get(fp);
730 if ((flp->l_start > 0 &&
731 foffset > OFF_MAX - flp->l_start) ||
733 foffset < OFF_MIN - flp->l_start)) {
738 flp->l_start += foffset;
741 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
747 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
750 error = fo_add_seals(fp, arg);
755 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
758 if (fo_get_seals(fp, &seals) == 0)
759 td->td_retval[0] = seals;
766 arg = arg ? 128 * 1024: 0;
769 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
772 if (fp->f_type != DTYPE_VNODE) {
778 if (vp->v_type != VREG) {
785 * Exclusive lock synchronizes against f_seqcount reads and
786 * writes in sequential_heuristic().
788 error = vn_lock(vp, LK_EXCLUSIVE);
794 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
795 arg = MIN(arg, INT_MAX - bsize + 1);
796 fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
797 (arg + bsize - 1) / bsize);
798 atomic_set_int(&fp->f_flag, FRDAHEAD);
800 atomic_clear_int(&fp->f_flag, FRDAHEAD);
808 * Check if the vnode is part of a union stack (either the
809 * "union" flag from mount(2) or unionfs).
811 * Prior to introduction of this op libc's readdir would call
812 * fstatfs(2), in effect unnecessarily copying kilobytes of
813 * data just to check fs name and a mount flag.
815 * Fixing the code to handle everything in the kernel instead
816 * is a non-trivial endeavor and has low priority, thus this
817 * horrible kludge facilitates the current behavior in a much
818 * cheaper manner until someone(tm) sorts this out.
820 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
823 if (fp->f_type != DTYPE_VNODE) {
830 * Since we don't prevent dooming the vnode even non-null mp
831 * found can become immediately stale. This is tolerable since
832 * mount points are type-stable (providing safe memory access)
833 * and any vfs op on this vnode going forward will return an
834 * error (meaning return value in this case is meaningless).
836 mp = atomic_load_ptr(&vp->v_mount);
837 if (__predict_false(mp == NULL)) {
842 td->td_retval[0] = 0;
843 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
844 mp->mnt_flag & MNT_UNION)
845 td->td_retval[0] = 1;
857 getmaxfd(struct thread *td)
860 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
864 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
867 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
869 struct filedesc *fdp;
870 struct filedescent *oldfde, *newfde;
873 u_long *oioctls, *nioctls;
880 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
881 MPASS(mode < FDDUP_LASTMODE);
884 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
887 * Verify we have a valid descriptor to dup from and possibly to
888 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
889 * return EINVAL when the new descriptor is out of bounds.
894 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
895 maxfd = getmaxfd(td);
897 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
901 if (fget_locked(fdp, old) == NULL)
903 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
904 td->td_retval[0] = new;
905 if (flags & FDDUP_FLAG_CLOEXEC)
906 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
911 oldfde = &fdp->fd_ofiles[old];
912 if (!fhold(oldfde->fde_file))
916 * If the caller specified a file descriptor, make sure the file
917 * table is large enough to hold it, and grab it. Otherwise, just
918 * allocate a new descriptor the usual way.
923 if ((error = fdalloc(td, new, &new)) != 0) {
924 fdrop(oldfde->fde_file, td);
928 case FDDUP_MUSTREPLACE:
929 /* Target file descriptor must exist. */
930 if (fget_locked(fdp, new) == NULL) {
931 fdrop(oldfde->fde_file, td);
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);
950 fdrop(oldfde->fde_file, td);
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 newfde = &fdp->fd_ofiles[new];
967 delfp = newfde->fde_file;
969 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
972 * Duplicate the source descriptor.
975 seqc_write_begin(&newfde->fde_seqc);
977 oioctls = filecaps_free_prep(&newfde->fde_caps);
978 memcpy(newfde, oldfde, fde_change_size);
979 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
981 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
982 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
984 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
986 seqc_write_end(&newfde->fde_seqc);
988 td->td_retval[0] = new;
993 (void) closefp(fdp, new, delfp, td, 1);
994 FILEDESC_UNLOCK_ASSERT(fdp);
997 FILEDESC_XUNLOCK(fdp);
1000 filecaps_free_finish(oioctls);
1005 * If sigio is on the list associated with a process or process group,
1006 * disable signalling from the device, remove sigio from the list and
1010 funsetown(struct sigio **sigiop)
1012 struct sigio *sigio;
1014 if (*sigiop == NULL)
1018 if (sigio == NULL) {
1022 *(sigio->sio_myref) = NULL;
1023 if ((sigio)->sio_pgid < 0) {
1024 struct pgrp *pg = (sigio)->sio_pgrp;
1026 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1027 sigio, sio_pgsigio);
1030 struct proc *p = (sigio)->sio_proc;
1032 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1033 sigio, sio_pgsigio);
1037 crfree(sigio->sio_ucred);
1038 free(sigio, M_SIGIO);
1042 * Free a list of sigio structures.
1043 * We only need to lock the SIGIO_LOCK because we have made ourselves
1044 * inaccessible to callers of fsetown and therefore do not need to lock
1045 * the proc or pgrp struct for the list manipulation.
1048 funsetownlst(struct sigiolst *sigiolst)
1052 struct sigio *sigio;
1054 sigio = SLIST_FIRST(sigiolst);
1061 * Every entry of the list should belong
1062 * to a single proc or pgrp.
1064 if (sigio->sio_pgid < 0) {
1065 pg = sigio->sio_pgrp;
1066 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1067 } else /* if (sigio->sio_pgid > 0) */ {
1068 p = sigio->sio_proc;
1069 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1073 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1074 *(sigio->sio_myref) = NULL;
1076 KASSERT(sigio->sio_pgid < 0,
1077 ("Proc sigio in pgrp sigio list"));
1078 KASSERT(sigio->sio_pgrp == pg,
1079 ("Bogus pgrp in sigio list"));
1081 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1084 } else /* if (p != NULL) */ {
1085 KASSERT(sigio->sio_pgid > 0,
1086 ("Pgrp sigio in proc sigio list"));
1087 KASSERT(sigio->sio_proc == p,
1088 ("Bogus proc in sigio list"));
1090 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1095 crfree(sigio->sio_ucred);
1096 free(sigio, M_SIGIO);
1103 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1105 * After permission checking, add a sigio structure to the sigio list for
1106 * the process or process group.
1109 fsetown(pid_t pgid, struct sigio **sigiop)
1113 struct sigio *sigio;
1123 /* Allocate and fill in the new sigio out of locks. */
1124 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1125 sigio->sio_pgid = pgid;
1126 sigio->sio_ucred = crhold(curthread->td_ucred);
1127 sigio->sio_myref = sigiop;
1129 sx_slock(&proctree_lock);
1138 * Policy - Don't allow a process to FSETOWN a process
1139 * in another session.
1141 * Remove this test to allow maximum flexibility or
1142 * restrict FSETOWN to the current process or process
1143 * group for maximum safety.
1146 if (proc->p_session != curthread->td_proc->p_session) {
1152 } else /* if (pgid < 0) */ {
1153 pgrp = pgfind(-pgid);
1161 * Policy - Don't allow a process to FSETOWN a process
1162 * in another session.
1164 * Remove this test to allow maximum flexibility or
1165 * restrict FSETOWN to the current process or process
1166 * group for maximum safety.
1168 if (pgrp->pg_session != curthread->td_proc->p_session) {
1179 * Since funsetownlst() is called without the proctree
1180 * locked, we need to check for P_WEXIT.
1181 * XXX: is ESRCH correct?
1183 if ((proc->p_flag & P_WEXIT) != 0) {
1188 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1189 sigio->sio_proc = proc;
1193 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1194 sigio->sio_pgrp = pgrp;
1197 sx_sunlock(&proctree_lock);
1204 sx_sunlock(&proctree_lock);
1205 crfree(sigio->sio_ucred);
1206 free(sigio, M_SIGIO);
1211 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1214 fgetown(struct sigio **sigiop)
1219 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1225 * Function drops the filedesc lock on return.
1228 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1233 FILEDESC_XLOCK_ASSERT(fdp);
1236 if (td->td_proc->p_fdtol != NULL) {
1238 * Ask fdfree() to sleep to ensure that all relevant
1239 * process leaders can be traversed in closef().
1241 fdp->fd_holdleaderscount++;
1248 * We now hold the fp reference that used to be owned by the
1249 * descriptor array. We have to unlock the FILEDESC *AFTER*
1250 * knote_fdclose to prevent a race of the fd getting opened, a knote
1251 * added, and deleteing a knote for the new fd.
1253 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1254 knote_fdclose(td, fd);
1257 * We need to notify mqueue if the object is of type mqueue.
1259 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1260 mq_fdclose(td, fd, fp);
1261 FILEDESC_XUNLOCK(fdp);
1263 error = closef(fp, td);
1265 FILEDESC_XLOCK(fdp);
1266 fdp->fd_holdleaderscount--;
1267 if (fdp->fd_holdleaderscount == 0 &&
1268 fdp->fd_holdleaderswakeup != 0) {
1269 fdp->fd_holdleaderswakeup = 0;
1270 wakeup(&fdp->fd_holdleaderscount);
1272 FILEDESC_XUNLOCK(fdp);
1278 * Close a file descriptor.
1280 #ifndef _SYS_SYSPROTO_H_
1287 sys_close(struct thread *td, struct close_args *uap)
1290 return (kern_close(td, uap->fd));
1294 kern_close(struct thread *td, int fd)
1296 struct filedesc *fdp;
1299 fdp = td->td_proc->p_fd;
1301 AUDIT_SYSCLOSE(td, fd);
1303 FILEDESC_XLOCK(fdp);
1304 if ((fp = fget_locked(fdp, fd)) == NULL) {
1305 FILEDESC_XUNLOCK(fdp);
1310 /* closefp() drops the FILEDESC lock for us. */
1311 return (closefp(fdp, fd, fp, td, 1));
1315 kern_close_range(struct thread *td, u_int lowfd, u_int highfd)
1317 struct filedesc *fdp;
1318 int fd, ret, lastfile;
1321 fdp = td->td_proc->p_fd;
1322 FILEDESC_SLOCK(fdp);
1325 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1326 * open should not be a usage error. From a close_range() perspective,
1327 * close_range(3, ~0U, 0) in the same scenario should also likely not
1328 * be a usage error as all fd above 3 are in-fact already closed.
1330 if (highfd < lowfd) {
1336 * If lastfile == -1, we're dealing with either a fresh file
1337 * table or one in which every fd has been closed. Just return
1338 * successful; there's nothing left to do.
1340 lastfile = fdlastfile(fdp);
1343 /* Clamped to [lowfd, lastfile] */
1344 highfd = MIN(highfd, lastfile);
1345 for (fd = lowfd; fd <= highfd; fd++) {
1346 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1347 FILEDESC_SUNLOCK(fdp);
1348 (void)kern_close(td, fd);
1349 FILEDESC_SLOCK(fdp);
1353 FILEDESC_SUNLOCK(fdp);
1357 #ifndef _SYS_SYSPROTO_H_
1358 struct close_range_args {
1365 sys_close_range(struct thread *td, struct close_range_args *uap)
1368 /* No flags currently defined */
1369 if (uap->flags != 0)
1371 return (kern_close_range(td, uap->lowfd, uap->highfd));
1374 #ifdef COMPAT_FREEBSD12
1376 * Close open file descriptors.
1378 #ifndef _SYS_SYSPROTO_H_
1379 struct freebsd12_closefrom_args {
1385 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1389 AUDIT_ARG_FD(uap->lowfd);
1392 * Treat negative starting file descriptor values identical to
1393 * closefrom(0) which closes all files.
1395 lowfd = MAX(0, uap->lowfd);
1396 return (kern_close_range(td, lowfd, ~0U));
1398 #endif /* COMPAT_FREEBSD12 */
1400 #if defined(COMPAT_43)
1402 * Return status information about a file descriptor.
1404 #ifndef _SYS_SYSPROTO_H_
1405 struct ofstat_args {
1412 ofstat(struct thread *td, struct ofstat_args *uap)
1418 error = kern_fstat(td, uap->fd, &ub);
1421 error = copyout(&oub, uap->sb, sizeof(oub));
1425 #endif /* COMPAT_43 */
1427 #if defined(COMPAT_FREEBSD11)
1429 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1432 struct freebsd11_stat osb;
1435 error = kern_fstat(td, uap->fd, &sb);
1438 error = freebsd11_cvtstat(&sb, &osb);
1440 error = copyout(&osb, uap->sb, sizeof(osb));
1443 #endif /* COMPAT_FREEBSD11 */
1446 * Return status information about a file descriptor.
1448 #ifndef _SYS_SYSPROTO_H_
1456 sys_fstat(struct thread *td, struct fstat_args *uap)
1461 error = kern_fstat(td, uap->fd, &ub);
1463 error = copyout(&ub, uap->sb, sizeof(ub));
1468 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1475 error = fget(td, fd, &cap_fstat_rights, &fp);
1476 if (__predict_false(error != 0))
1479 AUDIT_ARG_FILE(td->td_proc, fp);
1481 error = fo_stat(fp, sbp, td->td_ucred, td);
1483 #ifdef __STAT_TIME_T_EXT
1484 sbp->st_atim_ext = 0;
1485 sbp->st_mtim_ext = 0;
1486 sbp->st_ctim_ext = 0;
1487 sbp->st_btim_ext = 0;
1490 if (KTRPOINT(td, KTR_STRUCT))
1491 ktrstat_error(sbp, error);
1496 #if defined(COMPAT_FREEBSD11)
1498 * Return status information about a file descriptor.
1500 #ifndef _SYS_SYSPROTO_H_
1501 struct freebsd11_nfstat_args {
1508 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1514 error = kern_fstat(td, uap->fd, &ub);
1516 freebsd11_cvtnstat(&ub, &nub);
1517 error = copyout(&nub, uap->sb, sizeof(nub));
1521 #endif /* COMPAT_FREEBSD11 */
1524 * Return pathconf information about a file descriptor.
1526 #ifndef _SYS_SYSPROTO_H_
1527 struct fpathconf_args {
1534 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1539 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1541 td->td_retval[0] = value;
1546 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1552 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1556 if (name == _PC_ASYNC_IO) {
1557 *valuep = _POSIX_ASYNCHRONOUS_IO;
1562 vn_lock(vp, LK_SHARED | LK_RETRY);
1563 error = VOP_PATHCONF(vp, name, valuep);
1565 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1566 if (name != _PC_PIPE_BUF) {
1581 * Copy filecaps structure allocating memory for ioctls array if needed.
1583 * The last parameter indicates whether the fdtable is locked. If it is not and
1584 * ioctls are encountered, copying fails and the caller must lock the table.
1586 * Note that if the table was not locked, the caller has to check the relevant
1587 * sequence counter to determine whether the operation was successful.
1590 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1594 if (src->fc_ioctls != NULL && !locked)
1596 memcpy(dst, src, sizeof(*src));
1597 if (src->fc_ioctls == NULL)
1600 KASSERT(src->fc_nioctls > 0,
1601 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1603 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1604 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1605 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1610 filecaps_copy_prep(const struct filecaps *src)
1615 if (__predict_true(src->fc_ioctls == NULL))
1618 KASSERT(src->fc_nioctls > 0,
1619 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1621 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1622 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1627 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1633 if (__predict_true(src->fc_ioctls == NULL)) {
1634 MPASS(ioctls == NULL);
1638 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1639 dst->fc_ioctls = ioctls;
1640 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1644 * Move filecaps structure to the new place and clear the old place.
1647 filecaps_move(struct filecaps *src, struct filecaps *dst)
1651 bzero(src, sizeof(*src));
1655 * Fill the given filecaps structure with full rights.
1658 filecaps_fill(struct filecaps *fcaps)
1661 CAP_ALL(&fcaps->fc_rights);
1662 fcaps->fc_ioctls = NULL;
1663 fcaps->fc_nioctls = -1;
1664 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1668 * Free memory allocated within filecaps structure.
1671 filecaps_free(struct filecaps *fcaps)
1674 free(fcaps->fc_ioctls, M_FILECAPS);
1675 bzero(fcaps, sizeof(*fcaps));
1679 filecaps_free_prep(struct filecaps *fcaps)
1683 ioctls = fcaps->fc_ioctls;
1684 bzero(fcaps, sizeof(*fcaps));
1689 filecaps_free_finish(u_long *ioctls)
1692 free(ioctls, M_FILECAPS);
1696 * Validate the given filecaps structure.
1699 filecaps_validate(const struct filecaps *fcaps, const char *func)
1702 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1703 ("%s: invalid rights", func));
1704 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1705 ("%s: invalid fcntls", func));
1706 KASSERT(fcaps->fc_fcntls == 0 ||
1707 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1708 ("%s: fcntls without CAP_FCNTL", func));
1709 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1710 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1711 ("%s: invalid ioctls", func));
1712 KASSERT(fcaps->fc_nioctls == 0 ||
1713 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1714 ("%s: ioctls without CAP_IOCTL", func));
1718 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1722 FILEDESC_XLOCK_ASSERT(fdp);
1724 nfd1 = fdp->fd_nfiles * 2;
1727 fdgrowtable(fdp, nfd1);
1731 * Grow the file table to accommodate (at least) nfd descriptors.
1734 fdgrowtable(struct filedesc *fdp, int nfd)
1736 struct filedesc0 *fdp0;
1737 struct freetable *ft;
1738 struct fdescenttbl *ntable;
1739 struct fdescenttbl *otable;
1740 int nnfiles, onfiles;
1741 NDSLOTTYPE *nmap, *omap;
1743 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1745 /* save old values */
1746 onfiles = fdp->fd_nfiles;
1747 otable = fdp->fd_files;
1750 /* compute the size of the new table */
1751 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1752 if (nnfiles <= onfiles)
1753 /* the table is already large enough */
1757 * Allocate a new table. We need enough space for the number of
1758 * entries, file entries themselves and the struct freetable we will use
1759 * when we decommission the table and place it on the freelist.
1760 * We place the struct freetable in the middle so we don't have
1761 * to worry about padding.
1763 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1764 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1765 sizeof(struct freetable),
1766 M_FILEDESC, M_ZERO | M_WAITOK);
1767 /* copy the old data */
1768 ntable->fdt_nfiles = nnfiles;
1769 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1770 onfiles * sizeof(ntable->fdt_ofiles[0]));
1773 * Allocate a new map only if the old is not large enough. It will
1774 * grow at a slower rate than the table as it can map more
1775 * entries than the table can hold.
1777 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1778 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1780 /* copy over the old data and update the pointer */
1781 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1786 * Make sure that ntable is correctly initialized before we replace
1787 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1790 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1793 * Do not free the old file table, as some threads may still
1794 * reference entries within it. Instead, place it on a freelist
1795 * which will be processed when the struct filedesc is released.
1797 * Note that if onfiles == NDFILE, we're dealing with the original
1798 * static allocation contained within (struct filedesc0 *)fdp,
1799 * which must not be freed.
1801 if (onfiles > NDFILE) {
1802 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1803 fdp0 = (struct filedesc0 *)fdp;
1804 ft->ft_table = otable;
1805 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1808 * The map does not have the same possibility of threads still
1809 * holding references to it. So always free it as long as it
1810 * does not reference the original static allocation.
1812 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1813 free(omap, M_FILEDESC);
1817 * Allocate a file descriptor for the process.
1820 fdalloc(struct thread *td, int minfd, int *result)
1822 struct proc *p = td->td_proc;
1823 struct filedesc *fdp = p->p_fd;
1824 int fd, maxfd, allocfd;
1829 FILEDESC_XLOCK_ASSERT(fdp);
1831 if (fdp->fd_freefile > minfd)
1832 minfd = fdp->fd_freefile;
1834 maxfd = getmaxfd(td);
1837 * Search the bitmap for a free descriptor starting at minfd.
1838 * If none is found, grow the file table.
1840 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1841 if (__predict_false(fd >= maxfd))
1843 if (__predict_false(fd >= fdp->fd_nfiles)) {
1844 allocfd = min(fd * 2, maxfd);
1846 if (RACCT_ENABLED()) {
1847 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1853 * fd is already equal to first free descriptor >= minfd, so
1854 * we only need to grow the table and we are done.
1856 fdgrowtable_exp(fdp, allocfd);
1860 * Perform some sanity checks, then mark the file descriptor as
1861 * used and return it to the caller.
1863 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1864 ("invalid descriptor %d", fd));
1865 KASSERT(!fdisused(fdp, fd),
1866 ("fd_first_free() returned non-free descriptor"));
1867 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1868 ("file descriptor isn't free"));
1875 * Allocate n file descriptors for the process.
1878 fdallocn(struct thread *td, int minfd, int *fds, int n)
1880 struct proc *p = td->td_proc;
1881 struct filedesc *fdp = p->p_fd;
1884 FILEDESC_XLOCK_ASSERT(fdp);
1886 for (i = 0; i < n; i++)
1887 if (fdalloc(td, 0, &fds[i]) != 0)
1891 for (i--; i >= 0; i--)
1892 fdunused(fdp, fds[i]);
1900 * Create a new open file structure and allocate a file descriptor for the
1901 * process that refers to it. We add one reference to the file for the
1902 * descriptor table and one reference for resultfp. This is to prevent us
1903 * being preempted and the entry in the descriptor table closed after we
1904 * release the FILEDESC lock.
1907 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1908 struct filecaps *fcaps)
1913 error = falloc_noinstall(td, &fp);
1915 return (error); /* no reference held on error */
1917 error = finstall(td, fp, &fd, flags, fcaps);
1919 fdrop(fp, td); /* one reference (fp only) */
1923 if (resultfp != NULL)
1924 *resultfp = fp; /* copy out result */
1926 fdrop(fp, td); /* release local reference */
1928 if (resultfd != NULL)
1935 * Create a new open file structure without allocating a file descriptor.
1938 falloc_noinstall(struct thread *td, struct file **resultfp)
1941 int maxuserfiles = maxfiles - (maxfiles / 20);
1943 static struct timeval lastfail;
1946 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1948 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1949 if ((openfiles_new >= maxuserfiles &&
1950 priv_check(td, PRIV_MAXFILES) != 0) ||
1951 openfiles_new >= maxfiles) {
1952 atomic_subtract_int(&openfiles, 1);
1953 if (ppsratecheck(&lastfail, &curfail, 1)) {
1954 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1955 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1959 fp = uma_zalloc(file_zone, M_WAITOK);
1960 bzero(fp, sizeof(*fp));
1961 refcount_init(&fp->f_count, 1);
1962 fp->f_cred = crhold(td->td_ucred);
1963 fp->f_ops = &badfileops;
1969 * Install a file in a file descriptor table.
1972 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1973 struct filecaps *fcaps)
1975 struct filedescent *fde;
1979 filecaps_validate(fcaps, __func__);
1980 FILEDESC_XLOCK_ASSERT(fdp);
1982 fde = &fdp->fd_ofiles[fd];
1984 seqc_write_begin(&fde->fde_seqc);
1987 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1989 filecaps_move(fcaps, &fde->fde_caps);
1991 filecaps_fill(&fde->fde_caps);
1993 seqc_write_end(&fde->fde_seqc);
1998 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1999 struct filecaps *fcaps)
2001 struct filedesc *fdp = td->td_proc->p_fd;
2008 FILEDESC_XLOCK(fdp);
2009 error = fdalloc(td, 0, fd);
2010 if (__predict_false(error != 0)) {
2011 FILEDESC_XUNLOCK(fdp);
2015 _finstall(fdp, fp, *fd, flags, fcaps);
2016 FILEDESC_XUNLOCK(fdp);
2021 * Build a new filedesc structure from another.
2022 * Copy the current, root, and jail root vnode references.
2024 * If fdp is not NULL, return with it shared locked.
2027 fdinit(struct filedesc *fdp, bool prepfiles, int *lastfile)
2029 struct filedesc0 *newfdp0;
2030 struct filedesc *newfdp;
2034 MPASS(lastfile != NULL);
2036 MPASS(lastfile == NULL);
2038 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2039 newfdp = &newfdp0->fd_fd;
2041 /* Create the file descriptor table. */
2042 FILEDESC_LOCK_INIT(newfdp);
2043 refcount_init(&newfdp->fd_refcnt, 1);
2044 refcount_init(&newfdp->fd_holdcnt, 1);
2045 newfdp->fd_cmask = CMASK;
2046 newfdp->fd_map = newfdp0->fd_dmap;
2047 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2048 newfdp->fd_files->fdt_nfiles = NDFILE;
2051 newpwd = pwd_alloc();
2052 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2056 FILEDESC_SLOCK(fdp);
2057 newpwd = pwd_hold_filedesc(fdp);
2058 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2060 FILEDESC_SUNLOCK(fdp);
2065 *lastfile = fdlastfile(fdp);
2066 if (*lastfile < newfdp->fd_nfiles)
2068 FILEDESC_SUNLOCK(fdp);
2069 fdgrowtable(newfdp, *lastfile + 1);
2070 FILEDESC_SLOCK(fdp);
2076 static struct filedesc *
2077 fdhold(struct proc *p)
2079 struct filedesc *fdp;
2081 PROC_LOCK_ASSERT(p, MA_OWNED);
2084 refcount_acquire(&fdp->fd_holdcnt);
2089 fddrop(struct filedesc *fdp)
2092 if (fdp->fd_holdcnt > 1) {
2093 if (refcount_release(&fdp->fd_holdcnt) == 0)
2097 FILEDESC_LOCK_DESTROY(fdp);
2098 uma_zfree(filedesc0_zone, fdp);
2102 * Share a filedesc structure.
2105 fdshare(struct filedesc *fdp)
2108 refcount_acquire(&fdp->fd_refcnt);
2113 * Unshare a filedesc structure, if necessary by making a copy
2116 fdunshare(struct thread *td)
2118 struct filedesc *tmp;
2119 struct proc *p = td->td_proc;
2121 if (p->p_fd->fd_refcnt == 1)
2124 tmp = fdcopy(p->p_fd);
2130 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2134 td->td_proc->p_fd = fdp;
2138 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2139 * this is to ease callers, not catch errors.
2142 fdcopy(struct filedesc *fdp)
2144 struct filedesc *newfdp;
2145 struct filedescent *nfde, *ofde;
2150 newfdp = fdinit(fdp, true, &lastfile);
2151 /* copy all passable descriptors (i.e. not kqueue) */
2152 newfdp->fd_freefile = -1;
2153 for (i = 0; i <= lastfile; ++i) {
2154 ofde = &fdp->fd_ofiles[i];
2155 if (ofde->fde_file == NULL ||
2156 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2157 !fhold(ofde->fde_file)) {
2158 if (newfdp->fd_freefile == -1)
2159 newfdp->fd_freefile = i;
2162 nfde = &newfdp->fd_ofiles[i];
2164 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2165 fdused_init(newfdp, i);
2167 if (newfdp->fd_freefile == -1)
2168 newfdp->fd_freefile = i;
2169 newfdp->fd_cmask = fdp->fd_cmask;
2170 FILEDESC_SUNLOCK(fdp);
2175 * Copies a filedesc structure, while remapping all file descriptors
2176 * stored inside using a translation table.
2178 * File descriptors are copied over to the new file descriptor table,
2179 * regardless of whether the close-on-exec flag is set.
2182 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2183 struct filedesc **ret)
2185 struct filedesc *newfdp;
2186 struct filedescent *nfde, *ofde;
2187 int error, i, lastfile;
2191 newfdp = fdinit(fdp, true, &lastfile);
2192 if (nfds > lastfile + 1) {
2193 /* New table cannot be larger than the old one. */
2197 /* Copy all passable descriptors (i.e. not kqueue). */
2198 newfdp->fd_freefile = nfds;
2199 for (i = 0; i < nfds; ++i) {
2200 if (fds[i] < 0 || fds[i] > lastfile) {
2201 /* File descriptor out of bounds. */
2205 ofde = &fdp->fd_ofiles[fds[i]];
2206 if (ofde->fde_file == NULL) {
2207 /* Unused file descriptor. */
2211 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2212 /* File descriptor cannot be passed. */
2216 if (!fhold(ofde->fde_file)) {
2220 nfde = &newfdp->fd_ofiles[i];
2222 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2223 fdused_init(newfdp, i);
2225 newfdp->fd_cmask = fdp->fd_cmask;
2226 FILEDESC_SUNLOCK(fdp);
2230 FILEDESC_SUNLOCK(fdp);
2231 fdescfree_remapped(newfdp);
2236 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2237 * one of processes using it exits) and the table used to be shared.
2240 fdclearlocks(struct thread *td)
2242 struct filedesc *fdp;
2243 struct filedesc_to_leader *fdtol;
2253 MPASS(fdtol != NULL);
2255 FILEDESC_XLOCK(fdp);
2256 KASSERT(fdtol->fdl_refcount > 0,
2257 ("filedesc_to_refcount botch: fdl_refcount=%d",
2258 fdtol->fdl_refcount));
2259 if (fdtol->fdl_refcount == 1 &&
2260 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2261 lastfile = fdlastfile(fdp);
2262 for (i = 0; i <= lastfile; i++) {
2263 fp = fdp->fd_ofiles[i].fde_file;
2264 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2267 FILEDESC_XUNLOCK(fdp);
2268 lf.l_whence = SEEK_SET;
2271 lf.l_type = F_UNLCK;
2273 (void) VOP_ADVLOCK(vp,
2274 (caddr_t)p->p_leader, F_UNLCK,
2276 FILEDESC_XLOCK(fdp);
2281 if (fdtol->fdl_refcount == 1) {
2282 if (fdp->fd_holdleaderscount > 0 &&
2283 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2285 * close() or kern_dup() has cleared a reference
2286 * in a shared file descriptor table.
2288 fdp->fd_holdleaderswakeup = 1;
2289 sx_sleep(&fdp->fd_holdleaderscount,
2290 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2293 if (fdtol->fdl_holdcount > 0) {
2295 * Ensure that fdtol->fdl_leader remains
2296 * valid in closef().
2298 fdtol->fdl_wakeup = 1;
2299 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2304 fdtol->fdl_refcount--;
2305 if (fdtol->fdl_refcount == 0 &&
2306 fdtol->fdl_holdcount == 0) {
2307 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2308 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2312 FILEDESC_XUNLOCK(fdp);
2314 free(fdtol, M_FILEDESC_TO_LEADER);
2318 * Release a filedesc structure.
2321 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2323 struct filedesc0 *fdp0;
2324 struct freetable *ft, *tft;
2325 struct filedescent *fde;
2329 lastfile = fdlastfile_single(fdp);
2330 for (i = 0; i <= lastfile; i++) {
2331 fde = &fdp->fd_ofiles[i];
2336 (void) closef(fp, td);
2342 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2343 free(fdp->fd_map, M_FILEDESC);
2344 if (fdp->fd_nfiles > NDFILE)
2345 free(fdp->fd_files, M_FILEDESC);
2347 fdp0 = (struct filedesc0 *)fdp;
2348 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2349 free(ft->ft_table, M_FILEDESC);
2355 fdescfree(struct thread *td)
2358 struct filedesc *fdp;
2366 if (RACCT_ENABLED())
2367 racct_set_unlocked(p, RACCT_NOFILE, 0);
2370 if (p->p_fdtol != NULL)
2377 if (refcount_release(&fdp->fd_refcnt) == 0)
2380 FILEDESC_XLOCK(fdp);
2381 pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2383 FILEDESC_XUNLOCK(fdp);
2387 fdescfree_fds(td, fdp, 1);
2391 fdescfree_remapped(struct filedesc *fdp)
2394 pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2395 fdescfree_fds(curthread, fdp, 0);
2399 * For setugid programs, we don't want to people to use that setugidness
2400 * to generate error messages which write to a file which otherwise would
2401 * otherwise be off-limits to the process. We check for filesystems where
2402 * the vnode can change out from under us after execve (like [lin]procfs).
2404 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2405 * sufficient. We also don't check for setugidness since we know we are.
2408 is_unsafe(struct file *fp)
2412 if (fp->f_type != DTYPE_VNODE)
2416 return ((vp->v_vflag & VV_PROCDEP) != 0);
2420 * Make this setguid thing safe, if at all possible.
2423 fdsetugidsafety(struct thread *td)
2425 struct filedesc *fdp;
2429 fdp = td->td_proc->p_fd;
2430 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2431 MPASS(fdp->fd_nfiles >= 3);
2432 for (i = 0; i <= 2; i++) {
2433 fp = fdp->fd_ofiles[i].fde_file;
2434 if (fp != NULL && is_unsafe(fp)) {
2435 FILEDESC_XLOCK(fdp);
2436 knote_fdclose(td, i);
2438 * NULL-out descriptor prior to close to avoid
2439 * a race while close blocks.
2442 FILEDESC_XUNLOCK(fdp);
2443 (void) closef(fp, td);
2449 * If a specific file object occupies a specific file descriptor, close the
2450 * file descriptor entry and drop a reference on the file object. This is a
2451 * convenience function to handle a subsequent error in a function that calls
2452 * falloc() that handles the race that another thread might have closed the
2453 * file descriptor out from under the thread creating the file object.
2456 fdclose(struct thread *td, struct file *fp, int idx)
2458 struct filedesc *fdp = td->td_proc->p_fd;
2460 FILEDESC_XLOCK(fdp);
2461 if (fdp->fd_ofiles[idx].fde_file == fp) {
2463 FILEDESC_XUNLOCK(fdp);
2466 FILEDESC_XUNLOCK(fdp);
2470 * Close any files on exec?
2473 fdcloseexec(struct thread *td)
2475 struct filedesc *fdp;
2476 struct filedescent *fde;
2480 fdp = td->td_proc->p_fd;
2481 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2482 lastfile = fdlastfile_single(fdp);
2483 for (i = 0; i <= lastfile; i++) {
2484 fde = &fdp->fd_ofiles[i];
2486 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2487 (fde->fde_flags & UF_EXCLOSE))) {
2488 FILEDESC_XLOCK(fdp);
2490 (void) closefp(fdp, i, fp, td, 0);
2491 FILEDESC_UNLOCK_ASSERT(fdp);
2497 * It is unsafe for set[ug]id processes to be started with file
2498 * descriptors 0..2 closed, as these descriptors are given implicit
2499 * significance in the Standard C library. fdcheckstd() will create a
2500 * descriptor referencing /dev/null for each of stdin, stdout, and
2501 * stderr that is not already open.
2504 fdcheckstd(struct thread *td)
2506 struct filedesc *fdp;
2508 int i, error, devnull;
2510 fdp = td->td_proc->p_fd;
2511 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2512 MPASS(fdp->fd_nfiles >= 3);
2514 for (i = 0; i <= 2; i++) {
2515 if (fdp->fd_ofiles[i].fde_file != NULL)
2518 save = td->td_retval[0];
2519 if (devnull != -1) {
2520 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2522 error = kern_openat(td, AT_FDCWD, "/dev/null",
2523 UIO_SYSSPACE, O_RDWR, 0);
2525 devnull = td->td_retval[0];
2526 KASSERT(devnull == i, ("we didn't get our fd"));
2529 td->td_retval[0] = save;
2537 * Internal form of close. Decrement reference count on file structure.
2538 * Note: td may be NULL when closing a file that was being passed in a
2542 closef(struct file *fp, struct thread *td)
2546 struct filedesc_to_leader *fdtol;
2547 struct filedesc *fdp;
2550 * POSIX record locking dictates that any close releases ALL
2551 * locks owned by this process. This is handled by setting
2552 * a flag in the unlock to free ONLY locks obeying POSIX
2553 * semantics, and not to free BSD-style file locks.
2554 * If the descriptor was in a message, POSIX-style locks
2555 * aren't passed with the descriptor, and the thread pointer
2556 * will be NULL. Callers should be careful only to pass a
2557 * NULL thread pointer when there really is no owning
2558 * context that might have locks, or the locks will be
2561 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2563 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2564 lf.l_whence = SEEK_SET;
2567 lf.l_type = F_UNLCK;
2568 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2569 F_UNLCK, &lf, F_POSIX);
2571 fdtol = td->td_proc->p_fdtol;
2572 if (fdtol != NULL) {
2574 * Handle special case where file descriptor table is
2575 * shared between multiple process leaders.
2577 fdp = td->td_proc->p_fd;
2578 FILEDESC_XLOCK(fdp);
2579 for (fdtol = fdtol->fdl_next;
2580 fdtol != td->td_proc->p_fdtol;
2581 fdtol = fdtol->fdl_next) {
2582 if ((fdtol->fdl_leader->p_flag &
2585 fdtol->fdl_holdcount++;
2586 FILEDESC_XUNLOCK(fdp);
2587 lf.l_whence = SEEK_SET;
2590 lf.l_type = F_UNLCK;
2592 (void) VOP_ADVLOCK(vp,
2593 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2595 FILEDESC_XLOCK(fdp);
2596 fdtol->fdl_holdcount--;
2597 if (fdtol->fdl_holdcount == 0 &&
2598 fdtol->fdl_wakeup != 0) {
2599 fdtol->fdl_wakeup = 0;
2603 FILEDESC_XUNLOCK(fdp);
2606 return (fdrop(fp, td));
2610 * Initialize the file pointer with the specified properties.
2612 * The ops are set with release semantics to be certain that the flags, type,
2613 * and data are visible when ops is. This is to prevent ops methods from being
2614 * called with bad data.
2617 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2622 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2626 finit_vnode(struct file *fp, u_int flag, void *data, struct fileops *ops)
2628 fp->f_seqcount[UIO_READ] = 1;
2629 fp->f_seqcount[UIO_WRITE] = 1;
2630 finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2635 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2636 struct file **fpp, struct filecaps *havecapsp)
2638 struct filedescent *fde;
2641 FILEDESC_LOCK_ASSERT(fdp);
2643 fde = fdeget_locked(fdp, fd);
2650 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2655 if (havecapsp != NULL)
2656 filecaps_copy(&fde->fde_caps, havecapsp, true);
2658 *fpp = fde->fde_file;
2666 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2667 struct file **fpp, struct filecaps *havecapsp)
2669 struct filedesc *fdp = td->td_proc->p_fd;
2671 #ifndef CAPABILITIES
2672 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2673 if (havecapsp != NULL && error == 0)
2674 filecaps_fill(havecapsp);
2681 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2685 if (havecapsp != NULL) {
2686 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2687 havecapsp, false)) {
2693 if (!fd_modified(fdp, fd, seq))
2702 FILEDESC_SLOCK(fdp);
2703 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2704 if (error == 0 && !fhold(*fpp))
2706 FILEDESC_SUNLOCK(fdp);
2712 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2713 struct file **fpp, seqc_t *seqp)
2716 const struct filedescent *fde;
2718 const struct fdescenttbl *fdt;
2722 cap_rights_t haverights;
2726 fdt = fdp->fd_files;
2727 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2730 * Fetch the descriptor locklessly. We avoid fdrop() races by
2731 * never raising a refcount above 0. To accomplish this we have
2732 * to use a cmpset loop rather than an atomic_add. The descriptor
2733 * must be re-verified once we acquire a reference to be certain
2734 * that the identity is still correct and we did not lose a race
2735 * due to preemption.
2739 seq = seqc_read(fd_seqc(fdt, fd));
2740 fde = &fdt->fdt_ofiles[fd];
2741 haverights = *cap_rights_fde_inline(fde);
2743 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2746 fp = fdt->fdt_ofiles[fd].fde_file;
2751 error = cap_check_inline(&haverights, needrightsp);
2755 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2757 * The count was found either saturated or zero.
2758 * This re-read is not any more racy than using the
2759 * return value from fcmpset.
2761 if (fp->f_count != 0)
2764 * Force a reload. Other thread could reallocate the
2765 * table before this fd was closed, so it is possible
2766 * that there is a stale fp pointer in cached version.
2768 fdt = atomic_load_ptr(&fdp->fd_files);
2772 * Use an acquire barrier to force re-reading of fdt so it is
2773 * refreshed for verification.
2775 atomic_thread_fence_acq();
2776 fdt = fdp->fd_files;
2778 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2780 if (fp == fdt->fdt_ofiles[fd].fde_file)
2783 fdrop(fp, curthread);
2795 * See the comments in fget_unlocked_seq for an explanation of how this works.
2797 * This is a simplified variant which bails out to the aforementioned routine
2798 * if anything goes wrong. In practice this only happens when userspace is
2799 * racing with itself.
2802 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2806 const struct filedescent *fde;
2808 const struct fdescenttbl *fdt;
2812 const cap_rights_t *haverights;
2815 fdt = fdp->fd_files;
2816 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2819 seq = seqc_read_any(fd_seqc(fdt, fd));
2820 if (__predict_false(seqc_in_modify(seq)))
2822 fde = &fdt->fdt_ofiles[fd];
2823 haverights = cap_rights_fde_inline(fde);
2826 fp = fdt->fdt_ofiles[fd].fde_file;
2828 if (__predict_false(fp == NULL))
2831 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2834 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2838 * Use an acquire barrier to force re-reading of fdt so it is
2839 * refreshed for verification.
2841 atomic_thread_fence_acq();
2842 fdt = fdp->fd_files;
2844 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2846 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2852 fdrop(fp, curthread);
2854 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2858 * Extract the file pointer associated with the specified descriptor for the
2859 * current user process.
2861 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2864 * File's rights will be checked against the capability rights mask.
2866 * If an error occurred the non-zero error is returned and *fpp is set to
2867 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2868 * responsible for fdrop().
2871 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2872 cap_rights_t *needrightsp)
2874 struct filedesc *fdp;
2879 fdp = td->td_proc->p_fd;
2880 error = fget_unlocked(fdp, fd, needrightsp, &fp);
2881 if (__predict_false(error != 0))
2883 if (__predict_false(fp->f_ops == &badfileops)) {
2889 * FREAD and FWRITE failure return EBADF as per POSIX.
2895 if ((fp->f_flag & flags) == 0)
2899 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2900 ((fp->f_flag & FWRITE) != 0))
2906 KASSERT(0, ("wrong flags"));
2919 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2922 return (_fget(td, fd, fpp, 0, rightsp));
2926 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2930 #ifndef CAPABILITIES
2931 error = _fget(td, fd, fpp, 0, rightsp);
2932 if (maxprotp != NULL)
2933 *maxprotp = VM_PROT_ALL;
2936 cap_rights_t fdrights;
2937 struct filedesc *fdp;
2942 fdp = td->td_proc->p_fd;
2943 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2945 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2946 if (__predict_false(error != 0))
2948 if (__predict_false(fp->f_ops == &badfileops)) {
2952 if (maxprotp != NULL)
2953 fdrights = *cap_rights(fdp, fd);
2954 if (!fd_modified(fdp, fd, seq))
2960 * If requested, convert capability rights to access flags.
2962 if (maxprotp != NULL)
2963 *maxprotp = cap_rights_to_vmprot(&fdrights);
2970 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2973 return (_fget(td, fd, fpp, FREAD, rightsp));
2977 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2980 return (_fget(td, fd, fpp, FWRITE, rightsp));
2984 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2987 struct filedesc *fdp = td->td_proc->p_fd;
2988 #ifndef CAPABILITIES
2989 return (fget_unlocked(fdp, fd, rightsp, fpp));
2996 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2998 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
3001 error = cap_fcntl_check(fdp, fd, needfcntl);
3002 if (!fd_modified(fdp, fd, seq))
3016 * Like fget() but loads the underlying vnode, or returns an error if the
3017 * descriptor does not represent a vnode. Note that pipes use vnodes but
3018 * never have VM objects. The returned vnode will be vref()'d.
3020 * XXX: what about the unused flags ?
3023 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3030 error = _fget(td, fd, &fp, flags, needrightsp);
3033 if (fp->f_vnode == NULL) {
3045 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3048 return (_fgetvp(td, fd, 0, rightsp, vpp));
3052 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3053 struct filecaps *havecaps, struct vnode **vpp)
3055 struct filecaps caps;
3059 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3062 if (fp->f_ops == &badfileops) {
3066 if (fp->f_vnode == NULL) {
3078 filecaps_free(&caps);
3084 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3087 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3091 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3094 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3099 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3103 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3108 * Handle the last reference to a file being closed.
3110 * Without the noinline attribute clang keeps inlining the func thorough this
3111 * file when fdrop is used.
3114 _fdrop(struct file *fp, struct thread *td)
3118 if (fp->f_count != 0)
3119 panic("fdrop: count %d", fp->f_count);
3120 error = fo_close(fp, td);
3121 atomic_subtract_int(&openfiles, 1);
3123 free(fp->f_advice, M_FADVISE);
3124 uma_zfree(file_zone, fp);
3130 * Apply an advisory lock on a file descriptor.
3132 * Just attempt to get a record lock of the requested type on the entire file
3133 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3135 #ifndef _SYS_SYSPROTO_H_
3143 sys_flock(struct thread *td, struct flock_args *uap)
3150 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3153 if (fp->f_type != DTYPE_VNODE) {
3155 return (EOPNOTSUPP);
3159 lf.l_whence = SEEK_SET;
3162 if (uap->how & LOCK_UN) {
3163 lf.l_type = F_UNLCK;
3164 atomic_clear_int(&fp->f_flag, FHASLOCK);
3165 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3168 if (uap->how & LOCK_EX)
3169 lf.l_type = F_WRLCK;
3170 else if (uap->how & LOCK_SH)
3171 lf.l_type = F_RDLCK;
3176 atomic_set_int(&fp->f_flag, FHASLOCK);
3177 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3178 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3184 * Duplicate the specified descriptor to a free descriptor.
3187 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3188 int openerror, int *indxp)
3190 struct filedescent *newfde, *oldfde;
3195 KASSERT(openerror == ENODEV || openerror == ENXIO,
3196 ("unexpected error %d in %s", openerror, __func__));
3199 * If the to-be-dup'd fd number is greater than the allowed number
3200 * of file descriptors, or the fd to be dup'd has already been
3201 * closed, then reject.
3203 FILEDESC_XLOCK(fdp);
3204 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3205 FILEDESC_XUNLOCK(fdp);
3209 error = fdalloc(td, 0, &indx);
3211 FILEDESC_XUNLOCK(fdp);
3216 * There are two cases of interest here.
3218 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3220 * For ENXIO steal away the file structure from (dfd) and store it in
3221 * (indx). (dfd) is effectively closed by this operation.
3223 switch (openerror) {
3226 * Check that the mode the file is being opened for is a
3227 * subset of the mode of the existing descriptor.
3229 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3230 fdunused(fdp, indx);
3231 FILEDESC_XUNLOCK(fdp);
3235 fdunused(fdp, indx);
3236 FILEDESC_XUNLOCK(fdp);
3239 newfde = &fdp->fd_ofiles[indx];
3240 oldfde = &fdp->fd_ofiles[dfd];
3241 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3243 seqc_write_begin(&newfde->fde_seqc);
3245 memcpy(newfde, oldfde, fde_change_size);
3246 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3249 seqc_write_end(&newfde->fde_seqc);
3254 * Steal away the file pointer from dfd and stuff it into indx.
3256 newfde = &fdp->fd_ofiles[indx];
3257 oldfde = &fdp->fd_ofiles[dfd];
3259 seqc_write_begin(&newfde->fde_seqc);
3261 memcpy(newfde, oldfde, fde_change_size);
3262 oldfde->fde_file = NULL;
3265 seqc_write_end(&newfde->fde_seqc);
3269 FILEDESC_XUNLOCK(fdp);
3275 * This sysctl determines if we will allow a process to chroot(2) if it
3276 * has a directory open:
3277 * 0: disallowed for all processes.
3278 * 1: allowed for processes that were not already chroot(2)'ed.
3279 * 2: allowed for all processes.
3282 static int chroot_allow_open_directories = 1;
3284 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3285 &chroot_allow_open_directories, 0,
3286 "Allow a process to chroot(2) if it has a directory open");
3289 * Helper function for raised chroot(2) security function: Refuse if
3290 * any filedescriptors are open directories.
3293 chroot_refuse_vdir_fds(struct filedesc *fdp)
3299 FILEDESC_LOCK_ASSERT(fdp);
3301 lastfile = fdlastfile(fdp);
3302 for (fd = 0; fd <= lastfile; fd++) {
3303 fp = fget_locked(fdp, fd);
3306 if (fp->f_type == DTYPE_VNODE) {
3308 if (vp->v_type == VDIR)
3316 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3319 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3320 vrefact(oldpwd->pwd_cdir);
3321 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3324 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3325 vrefact(oldpwd->pwd_rdir);
3326 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3329 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3330 vrefact(oldpwd->pwd_jdir);
3331 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3336 pwd_hold_filedesc(struct filedesc *fdp)
3340 FILEDESC_LOCK_ASSERT(fdp);
3341 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3343 refcount_acquire(&pwd->pwd_refcount);
3348 pwd_hold_smr(struct pwd *pwd)
3352 if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3359 pwd_hold(struct thread *td)
3361 struct filedesc *fdp;
3364 fdp = td->td_proc->p_fd;
3367 pwd = vfs_smr_entered_load(&fdp->fd_pwd);
3368 if (pwd_hold_smr(pwd)) {
3373 FILEDESC_SLOCK(fdp);
3374 pwd = pwd_hold_filedesc(fdp);
3376 FILEDESC_SUNLOCK(fdp);
3385 pwd = vfs_smr_entered_load(&curproc->p_fd->fd_pwd);
3395 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3396 bzero(pwd, sizeof(*pwd));
3397 refcount_init(&pwd->pwd_refcount, 1);
3402 pwd_drop(struct pwd *pwd)
3405 if (!refcount_release(&pwd->pwd_refcount))
3408 if (pwd->pwd_cdir != NULL)
3409 vrele(pwd->pwd_cdir);
3410 if (pwd->pwd_rdir != NULL)
3411 vrele(pwd->pwd_rdir);
3412 if (pwd->pwd_jdir != NULL)
3413 vrele(pwd->pwd_jdir);
3414 uma_zfree_smr(pwd_zone, pwd);
3418 * Common routine for kern_chroot() and jail_attach(). The caller is
3419 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3420 * authorize this operation.
3423 pwd_chroot(struct thread *td, struct vnode *vp)
3425 struct filedesc *fdp;
3426 struct pwd *newpwd, *oldpwd;
3429 fdp = td->td_proc->p_fd;
3430 newpwd = pwd_alloc();
3431 FILEDESC_XLOCK(fdp);
3432 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3433 if (chroot_allow_open_directories == 0 ||
3434 (chroot_allow_open_directories == 1 &&
3435 oldpwd->pwd_rdir != rootvnode)) {
3436 error = chroot_refuse_vdir_fds(fdp);
3438 FILEDESC_XUNLOCK(fdp);
3445 newpwd->pwd_rdir = vp;
3446 if (oldpwd->pwd_jdir == NULL) {
3448 newpwd->pwd_jdir = vp;
3450 pwd_fill(oldpwd, newpwd);
3451 pwd_set(fdp, newpwd);
3452 FILEDESC_XUNLOCK(fdp);
3458 pwd_chdir(struct thread *td, struct vnode *vp)
3460 struct filedesc *fdp;
3461 struct pwd *newpwd, *oldpwd;
3463 VNPASS(vp->v_usecount > 0, vp);
3465 newpwd = pwd_alloc();
3466 fdp = td->td_proc->p_fd;
3467 FILEDESC_XLOCK(fdp);
3468 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3469 newpwd->pwd_cdir = vp;
3470 pwd_fill(oldpwd, newpwd);
3471 pwd_set(fdp, newpwd);
3472 FILEDESC_XUNLOCK(fdp);
3477 pwd_ensure_dirs(void)
3479 struct filedesc *fdp;
3480 struct pwd *oldpwd, *newpwd;
3482 fdp = curproc->p_fd;
3483 FILEDESC_XLOCK(fdp);
3484 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3485 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3486 FILEDESC_XUNLOCK(fdp);
3489 FILEDESC_XUNLOCK(fdp);
3491 newpwd = pwd_alloc();
3492 FILEDESC_XLOCK(fdp);
3493 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3494 pwd_fill(oldpwd, newpwd);
3495 if (newpwd->pwd_cdir == NULL) {
3497 newpwd->pwd_cdir = rootvnode;
3499 if (newpwd->pwd_rdir == NULL) {
3501 newpwd->pwd_rdir = rootvnode;
3503 pwd_set(fdp, newpwd);
3504 FILEDESC_XUNLOCK(fdp);
3509 pwd_set_rootvnode(void)
3511 struct filedesc *fdp;
3512 struct pwd *oldpwd, *newpwd;
3514 fdp = curproc->p_fd;
3516 newpwd = pwd_alloc();
3517 FILEDESC_XLOCK(fdp);
3518 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3520 newpwd->pwd_cdir = rootvnode;
3522 newpwd->pwd_rdir = rootvnode;
3523 pwd_fill(oldpwd, newpwd);
3524 pwd_set(fdp, newpwd);
3525 FILEDESC_XUNLOCK(fdp);
3530 * Scan all active processes and prisons to see if any of them have a current
3531 * or root directory of `olddp'. If so, replace them with the new mount point.
3534 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3536 struct filedesc *fdp;
3537 struct pwd *newpwd, *oldpwd;
3542 if (vrefcnt(olddp) == 1)
3545 newpwd = pwd_alloc();
3546 sx_slock(&allproc_lock);
3547 FOREACH_PROC_IN_SYSTEM(p) {
3553 FILEDESC_XLOCK(fdp);
3554 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3555 if (oldpwd == NULL ||
3556 (oldpwd->pwd_cdir != olddp &&
3557 oldpwd->pwd_rdir != olddp &&
3558 oldpwd->pwd_jdir != olddp)) {
3559 FILEDESC_XUNLOCK(fdp);
3563 if (oldpwd->pwd_cdir == olddp) {
3565 newpwd->pwd_cdir = newdp;
3567 if (oldpwd->pwd_rdir == olddp) {
3569 newpwd->pwd_rdir = newdp;
3571 if (oldpwd->pwd_jdir == olddp) {
3573 newpwd->pwd_jdir = newdp;
3575 pwd_fill(oldpwd, newpwd);
3576 pwd_set(fdp, newpwd);
3577 FILEDESC_XUNLOCK(fdp);
3580 newpwd = pwd_alloc();
3582 sx_sunlock(&allproc_lock);
3584 if (rootvnode == olddp) {
3589 mtx_lock(&prison0.pr_mtx);
3590 if (prison0.pr_root == olddp) {
3592 prison0.pr_root = newdp;
3595 mtx_unlock(&prison0.pr_mtx);
3596 sx_slock(&allprison_lock);
3597 TAILQ_FOREACH(pr, &allprison, pr_list) {
3598 mtx_lock(&pr->pr_mtx);
3599 if (pr->pr_root == olddp) {
3601 pr->pr_root = newdp;
3604 mtx_unlock(&pr->pr_mtx);
3606 sx_sunlock(&allprison_lock);
3611 struct filedesc_to_leader *
3612 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3614 struct filedesc_to_leader *fdtol;
3616 fdtol = malloc(sizeof(struct filedesc_to_leader),
3617 M_FILEDESC_TO_LEADER, M_WAITOK);
3618 fdtol->fdl_refcount = 1;
3619 fdtol->fdl_holdcount = 0;
3620 fdtol->fdl_wakeup = 0;
3621 fdtol->fdl_leader = leader;
3623 FILEDESC_XLOCK(fdp);
3624 fdtol->fdl_next = old->fdl_next;
3625 fdtol->fdl_prev = old;
3626 old->fdl_next = fdtol;
3627 fdtol->fdl_next->fdl_prev = fdtol;
3628 FILEDESC_XUNLOCK(fdp);
3630 fdtol->fdl_next = fdtol;
3631 fdtol->fdl_prev = fdtol;
3637 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3640 struct filedesc *fdp;
3641 int count, off, minoff;
3643 if (*(int *)arg1 != 0)
3646 fdp = curproc->p_fd;
3648 FILEDESC_SLOCK(fdp);
3650 off = NDSLOT(fdp->fd_nfiles - 1);
3651 for (minoff = NDSLOT(0); off >= minoff; --off)
3652 count += bitcountl(map[off]);
3653 FILEDESC_SUNLOCK(fdp);
3655 return (SYSCTL_OUT(req, &count, sizeof(count)));
3658 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3659 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3660 "Number of open file descriptors");
3663 * Get file structures globally.
3666 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3669 struct filedesc *fdp;
3672 int error, n, lastfile;
3674 error = sysctl_wire_old_buffer(req, 0);
3677 if (req->oldptr == NULL) {
3679 sx_slock(&allproc_lock);
3680 FOREACH_PROC_IN_SYSTEM(p) {
3682 if (p->p_state == PRS_NEW) {
3690 /* overestimates sparse tables. */
3691 n += fdp->fd_nfiles;
3694 sx_sunlock(&allproc_lock);
3695 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3698 bzero(&xf, sizeof(xf));
3699 xf.xf_size = sizeof(xf);
3700 sx_slock(&allproc_lock);
3701 FOREACH_PROC_IN_SYSTEM(p) {
3703 if (p->p_state == PRS_NEW) {
3707 if (p_cansee(req->td, p) != 0) {
3711 xf.xf_pid = p->p_pid;
3712 xf.xf_uid = p->p_ucred->cr_uid;
3717 FILEDESC_SLOCK(fdp);
3718 lastfile = fdlastfile(fdp);
3719 for (n = 0; fdp->fd_refcnt > 0 && n <= lastfile; ++n) {
3720 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3723 xf.xf_file = (uintptr_t)fp;
3724 xf.xf_data = (uintptr_t)fp->f_data;
3725 xf.xf_vnode = (uintptr_t)fp->f_vnode;
3726 xf.xf_type = (uintptr_t)fp->f_type;
3727 xf.xf_count = fp->f_count;
3729 xf.xf_offset = foffset_get(fp);
3730 xf.xf_flag = fp->f_flag;
3731 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3735 FILEDESC_SUNLOCK(fdp);
3740 sx_sunlock(&allproc_lock);
3744 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3745 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3747 #ifdef KINFO_FILE_SIZE
3748 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3752 xlate_fflags(int fflags)
3754 static const struct {
3757 } fflags_table[] = {
3758 { FAPPEND, KF_FLAG_APPEND },
3759 { FASYNC, KF_FLAG_ASYNC },
3760 { FFSYNC, KF_FLAG_FSYNC },
3761 { FHASLOCK, KF_FLAG_HASLOCK },
3762 { FNONBLOCK, KF_FLAG_NONBLOCK },
3763 { FREAD, KF_FLAG_READ },
3764 { FWRITE, KF_FLAG_WRITE },
3765 { O_CREAT, KF_FLAG_CREAT },
3766 { O_DIRECT, KF_FLAG_DIRECT },
3767 { O_EXCL, KF_FLAG_EXCL },
3768 { O_EXEC, KF_FLAG_EXEC },
3769 { O_EXLOCK, KF_FLAG_EXLOCK },
3770 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3771 { O_SHLOCK, KF_FLAG_SHLOCK },
3772 { O_TRUNC, KF_FLAG_TRUNC }
3778 for (i = 0; i < nitems(fflags_table); i++)
3779 if (fflags & fflags_table[i].fflag)
3780 kflags |= fflags_table[i].kf_fflag;
3784 /* Trim unused data from kf_path by truncating the structure size. */
3786 pack_kinfo(struct kinfo_file *kif)
3789 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3790 strlen(kif->kf_path) + 1;
3791 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3795 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3796 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3800 bzero(kif, sizeof(*kif));
3802 /* Set a default type to allow for empty fill_kinfo() methods. */
3803 kif->kf_type = KF_TYPE_UNKNOWN;
3804 kif->kf_flags = xlate_fflags(fp->f_flag);
3805 if (rightsp != NULL)
3806 kif->kf_cap_rights = *rightsp;
3808 cap_rights_init_zero(&kif->kf_cap_rights);
3810 kif->kf_ref_count = fp->f_count;
3811 kif->kf_offset = foffset_get(fp);
3814 * This may drop the filedesc lock, so the 'fp' cannot be
3815 * accessed after this call.
3817 error = fo_fill_kinfo(fp, kif, fdp);
3819 kif->kf_status |= KF_ATTR_VALID;
3820 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3823 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3827 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3828 struct kinfo_file *kif, int flags)
3832 bzero(kif, sizeof(*kif));
3834 kif->kf_type = KF_TYPE_VNODE;
3835 error = vn_fill_kinfo_vnode(vp, kif);
3837 kif->kf_status |= KF_ATTR_VALID;
3838 kif->kf_flags = xlate_fflags(fflags);
3839 cap_rights_init_zero(&kif->kf_cap_rights);
3841 kif->kf_ref_count = -1;
3842 kif->kf_offset = -1;
3843 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3846 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3850 struct export_fd_buf {
3851 struct filedesc *fdp;
3854 struct kinfo_file kif;
3859 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3861 struct kinfo_file *kif;
3864 if (efbuf->remainder != -1) {
3865 if (efbuf->remainder < kif->kf_structsize) {
3866 /* Terminate export. */
3867 efbuf->remainder = 0;
3870 efbuf->remainder -= kif->kf_structsize;
3872 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3876 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3877 struct export_fd_buf *efbuf)
3881 if (efbuf->remainder == 0)
3883 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3885 FILEDESC_SUNLOCK(efbuf->fdp);
3886 error = export_kinfo_to_sb(efbuf);
3887 FILEDESC_SLOCK(efbuf->fdp);
3892 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3893 struct export_fd_buf *efbuf)
3897 if (efbuf->remainder == 0)
3899 if (efbuf->fdp != NULL)
3900 FILEDESC_SUNLOCK(efbuf->fdp);
3901 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3902 error = export_kinfo_to_sb(efbuf);
3903 if (efbuf->fdp != NULL)
3904 FILEDESC_SLOCK(efbuf->fdp);
3909 * Store a process file descriptor information to sbuf.
3911 * Takes a locked proc as argument, and returns with the proc unlocked.
3914 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3918 struct filedesc *fdp;
3919 struct export_fd_buf *efbuf;
3920 struct vnode *cttyvp, *textvp, *tracevp;
3922 int error, i, lastfile;
3923 cap_rights_t rights;
3925 PROC_LOCK_ASSERT(p, MA_OWNED);
3928 tracevp = p->p_tracevp;
3929 if (tracevp != NULL)
3932 textvp = p->p_textvp;
3935 /* Controlling tty. */
3937 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3938 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3944 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3947 efbuf->remainder = maxlen;
3948 efbuf->flags = flags;
3949 if (tracevp != NULL)
3950 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3953 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3955 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3961 FILEDESC_SLOCK(fdp);
3962 pwd = pwd_hold_filedesc(fdp);
3964 /* working directory */
3965 if (pwd->pwd_cdir != NULL) {
3966 vrefact(pwd->pwd_cdir);
3967 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3969 /* root directory */
3970 if (pwd->pwd_rdir != NULL) {
3971 vrefact(pwd->pwd_rdir);
3972 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3974 /* jail directory */
3975 if (pwd->pwd_jdir != NULL) {
3976 vrefact(pwd->pwd_jdir);
3977 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3980 lastfile = fdlastfile(fdp);
3981 for (i = 0; fdp->fd_refcnt > 0 && i <= lastfile; i++) {
3982 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3985 rights = *cap_rights(fdp, i);
3986 #else /* !CAPABILITIES */
3987 rights = cap_no_rights;
3990 * Create sysctl entry. It is OK to drop the filedesc
3991 * lock inside of export_file_to_sb() as we will
3992 * re-validate and re-evaluate its properties when the
3995 error = export_file_to_sb(fp, i, &rights, efbuf);
3996 if (error != 0 || efbuf->remainder == 0)
3999 FILEDESC_SUNLOCK(fdp);
4004 free(efbuf, M_TEMP);
4008 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
4011 * Get per-process file descriptors for use by procstat(1), et al.
4014 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4019 int error, error2, *name;
4023 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4024 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4025 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4030 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4031 error = kern_proc_filedesc_out(p, &sb, maxlen,
4032 KERN_FILEDESC_PACK_KINFO);
4033 error2 = sbuf_finish(&sb);
4035 return (error != 0 ? error : error2);
4038 #ifdef COMPAT_FREEBSD7
4039 #ifdef KINFO_OFILE_SIZE
4040 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4044 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4047 okif->kf_structsize = sizeof(*okif);
4048 okif->kf_type = kif->kf_type;
4049 okif->kf_fd = kif->kf_fd;
4050 okif->kf_ref_count = kif->kf_ref_count;
4051 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4052 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4053 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4054 okif->kf_offset = kif->kf_offset;
4055 if (kif->kf_type == KF_TYPE_VNODE)
4056 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4058 okif->kf_vnode_type = KF_VTYPE_VNON;
4059 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4060 if (kif->kf_type == KF_TYPE_SOCKET) {
4061 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4062 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4063 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4064 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4065 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4067 okif->kf_sa_local.ss_family = AF_UNSPEC;
4068 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4073 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4074 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
4079 FILEDESC_SUNLOCK(fdp);
4080 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4081 kinfo_to_okinfo(kif, okif);
4082 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4083 FILEDESC_SLOCK(fdp);
4088 * Get per-process file descriptors for use by procstat(1), et al.
4091 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4093 struct kinfo_ofile *okif;
4094 struct kinfo_file *kif;
4095 struct filedesc *fdp;
4097 int error, i, lastfile, *name;
4102 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4109 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4110 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4111 FILEDESC_SLOCK(fdp);
4112 pwd = pwd_hold_filedesc(fdp);
4114 if (pwd->pwd_cdir != NULL)
4115 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4117 if (pwd->pwd_rdir != NULL)
4118 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4120 if (pwd->pwd_jdir != NULL)
4121 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4124 lastfile = fdlastfile(fdp);
4125 for (i = 0; fdp->fd_refcnt > 0 && i <= lastfile; i++) {
4126 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4128 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4129 KERN_FILEDESC_PACK_KINFO);
4130 FILEDESC_SUNLOCK(fdp);
4131 kinfo_to_okinfo(kif, okif);
4132 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4133 FILEDESC_SLOCK(fdp);
4137 FILEDESC_SUNLOCK(fdp);
4146 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4147 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4148 "Process ofiledesc entries");
4149 #endif /* COMPAT_FREEBSD7 */
4152 vntype_to_kinfo(int vtype)
4157 } vtypes_table[] = {
4158 { VBAD, KF_VTYPE_VBAD },
4159 { VBLK, KF_VTYPE_VBLK },
4160 { VCHR, KF_VTYPE_VCHR },
4161 { VDIR, KF_VTYPE_VDIR },
4162 { VFIFO, KF_VTYPE_VFIFO },
4163 { VLNK, KF_VTYPE_VLNK },
4164 { VNON, KF_VTYPE_VNON },
4165 { VREG, KF_VTYPE_VREG },
4166 { VSOCK, KF_VTYPE_VSOCK }
4171 * Perform vtype translation.
4173 for (i = 0; i < nitems(vtypes_table); i++)
4174 if (vtypes_table[i].vtype == vtype)
4175 return (vtypes_table[i].kf_vtype);
4177 return (KF_VTYPE_UNKNOWN);
4180 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4181 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4182 "Process filedesc entries");
4185 * Store a process current working directory information to sbuf.
4187 * Takes a locked proc as argument, and returns with the proc unlocked.
4190 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4192 struct filedesc *fdp;
4194 struct export_fd_buf *efbuf;
4198 PROC_LOCK_ASSERT(p, MA_OWNED);
4205 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4208 efbuf->remainder = maxlen;
4210 FILEDESC_SLOCK(fdp);
4211 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4212 cdir = pwd->pwd_cdir;
4217 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4219 FILEDESC_SUNLOCK(fdp);
4221 free(efbuf, M_TEMP);
4226 * Get per-process current working directory.
4229 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4234 int error, error2, *name;
4238 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4239 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4240 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4245 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4246 error = kern_proc_cwd_out(p, &sb, maxlen);
4247 error2 = sbuf_finish(&sb);
4249 return (error != 0 ? error : error2);
4252 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4253 sysctl_kern_proc_cwd, "Process current working directory");
4257 * For the purposes of debugging, generate a human-readable string for the
4261 file_type_to_name(short type)
4289 case DTYPE_PROCDESC:
4291 case DTYPE_LINUXEFD:
4293 case DTYPE_LINUXTFD:
4301 * For the purposes of debugging, identify a process (if any, perhaps one of
4302 * many) that references the passed file in its file descriptor array. Return
4305 static struct proc *
4306 file_to_first_proc(struct file *fp)
4308 struct filedesc *fdp;
4312 FOREACH_PROC_IN_SYSTEM(p) {
4313 if (p->p_state == PRS_NEW)
4318 for (n = 0; n < fdp->fd_nfiles; n++) {
4319 if (fp == fdp->fd_ofiles[n].fde_file)
4327 db_print_file(struct file *fp, int header)
4329 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4333 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4334 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4335 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4337 p = file_to_first_proc(fp);
4338 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4339 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4340 fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4341 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4346 DB_SHOW_COMMAND(file, db_show_file)
4351 db_printf("usage: show file <addr>\n");
4354 fp = (struct file *)addr;
4355 db_print_file(fp, 1);
4358 DB_SHOW_COMMAND(files, db_show_files)
4360 struct filedesc *fdp;
4367 FOREACH_PROC_IN_SYSTEM(p) {
4368 if (p->p_state == PRS_NEW)
4370 if ((fdp = p->p_fd) == NULL)
4372 for (n = 0; n < fdp->fd_nfiles; ++n) {
4373 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4375 db_print_file(fp, header);
4382 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4383 &maxfilesperproc, 0, "Maximum files allowed open per process");
4385 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4386 &maxfiles, 0, "Maximum number of files");
4388 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4389 &openfiles, 0, "System-wide number of open files");
4393 filelistinit(void *dummy)
4396 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4397 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4398 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4399 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4400 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4401 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4403 * XXXMJG this is a temporary hack due to boot ordering issues against
4406 vfs_smr = uma_zone_get_smr(pwd_zone);
4407 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4409 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4411 /*-------------------------------------------------------------------*/
4414 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4415 int flags, struct thread *td)
4422 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4430 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4438 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4446 badfo_kqfilter(struct file *fp, struct knote *kn)
4453 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4461 badfo_close(struct file *fp, struct thread *td)
4468 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4476 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4484 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4485 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4493 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4499 struct fileops badfileops = {
4500 .fo_read = badfo_readwrite,
4501 .fo_write = badfo_readwrite,
4502 .fo_truncate = badfo_truncate,
4503 .fo_ioctl = badfo_ioctl,
4504 .fo_poll = badfo_poll,
4505 .fo_kqfilter = badfo_kqfilter,
4506 .fo_stat = badfo_stat,
4507 .fo_close = badfo_close,
4508 .fo_chmod = badfo_chmod,
4509 .fo_chown = badfo_chown,
4510 .fo_sendfile = badfo_sendfile,
4511 .fo_fill_kinfo = badfo_fill_kinfo,
4515 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4516 int flags, struct thread *td)
4519 return (EOPNOTSUPP);
4523 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4531 invfo_ioctl(struct file *fp, u_long com, void *data,
4532 struct ucred *active_cred, struct thread *td)
4539 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4543 return (poll_no_poll(events));
4547 invfo_kqfilter(struct file *fp, struct knote *kn)
4554 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4562 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4570 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4571 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4578 /*-------------------------------------------------------------------*/
4581 * File Descriptor pseudo-device driver (/dev/fd/).
4583 * Opening minor device N dup()s the file (if any) connected to file
4584 * descriptor N belonging to the calling process. Note that this driver
4585 * consists of only the ``open()'' routine, because all subsequent
4586 * references to this file will be direct to the other driver.
4588 * XXX: we could give this one a cloning event handler if necessary.
4593 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4597 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4598 * the file descriptor being sought for duplication. The error
4599 * return ensures that the vnode for this device will be released
4600 * by vn_open. Open will detect this special error and take the
4601 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4602 * will simply report the error.
4604 td->td_dupfd = dev2unit(dev);
4608 static struct cdevsw fildesc_cdevsw = {
4609 .d_version = D_VERSION,
4615 fildesc_drvinit(void *unused)
4619 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4620 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4621 make_dev_alias(dev, "stdin");
4622 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4623 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4624 make_dev_alias(dev, "stdout");
4625 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4626 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4627 make_dev_alias(dev, "stderr");
4630 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);