2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
44 #include "opt_ktrace.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capsicum.h>
51 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
56 #include <sys/kernel.h>
57 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/selinfo.h>
66 #include <sys/protosw.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
70 #include <sys/signalvar.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysproto.h>
78 #include <sys/unistd.h>
80 #include <sys/vnode.h>
82 #include <sys/ktrace.h>
87 #include <security/audit/audit.h>
94 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
95 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
96 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
97 "file desc to leader structures");
98 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
99 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
101 MALLOC_DECLARE(M_FADVISE);
103 static __read_mostly uma_zone_t file_zone;
104 static __read_mostly uma_zone_t filedesc0_zone;
105 static __read_mostly uma_zone_t pwd_zone;
106 static __read_mostly smr_t pwd_smr;
108 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
109 struct thread *td, int holdleaders);
110 static int fd_first_free(struct filedesc *fdp, int low, int size);
111 static int fd_last_used(struct filedesc *fdp, int size);
112 static void fdgrowtable(struct filedesc *fdp, int nfd);
113 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
114 static void fdunused(struct filedesc *fdp, int fd);
115 static void fdused(struct filedesc *fdp, int fd);
116 static int getmaxfd(struct thread *td);
117 static u_long *filecaps_copy_prep(const struct filecaps *src);
118 static void filecaps_copy_finish(const struct filecaps *src,
119 struct filecaps *dst, u_long *ioctls);
120 static u_long *filecaps_free_prep(struct filecaps *fcaps);
121 static void filecaps_free_finish(u_long *ioctls);
123 static struct pwd *pwd_alloc(void);
128 * - An array of open file descriptors (fd_ofiles)
129 * - An array of file flags (fd_ofileflags)
130 * - A bitmap recording which descriptors are in use (fd_map)
132 * A process starts out with NDFILE descriptors. The value of NDFILE has
133 * been selected based the historical limit of 20 open files, and an
134 * assumption that the majority of processes, especially short-lived
135 * processes like shells, will never need more.
137 * If this initial allocation is exhausted, a larger descriptor table and
138 * map are allocated dynamically, and the pointers in the process's struct
139 * filedesc are updated to point to those. This is repeated every time
140 * the process runs out of file descriptors (provided it hasn't hit its
143 * Since threads may hold references to individual descriptor table
144 * entries, the tables are never freed. Instead, they are placed on a
145 * linked list and freed only when the struct filedesc is released.
148 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
149 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
150 #define NDSLOT(x) ((x) / NDENTRIES)
151 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
152 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
155 * SLIST entry used to keep track of ofiles which must be reclaimed when
159 struct fdescenttbl *ft_table;
160 SLIST_ENTRY(freetable) ft_next;
164 * Initial allocation: a filedesc structure + the head of SLIST used to
165 * keep track of old ofiles + enough space for NDFILE descriptors.
168 struct fdescenttbl0 {
170 struct filedescent fdt_ofiles[NDFILE];
174 struct filedesc fd_fd;
175 SLIST_HEAD(, freetable) fd_free;
176 struct fdescenttbl0 fd_dfiles;
177 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
181 * Descriptor management.
183 static int __exclusive_cache_line openfiles; /* actual number of open files */
184 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
185 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
188 * If low >= size, just return low. Otherwise find the first zero bit in the
189 * given bitmap, starting at low and not exceeding size - 1. Return size if
193 fd_first_free(struct filedesc *fdp, int low, int size)
195 NDSLOTTYPE *map = fdp->fd_map;
203 if (low % NDENTRIES) {
204 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
205 if ((mask &= ~map[off]) != 0UL)
206 return (off * NDENTRIES + ffsl(mask) - 1);
209 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
210 if (map[off] != ~0UL)
211 return (off * NDENTRIES + ffsl(~map[off]) - 1);
216 * Find the highest non-zero bit in the given bitmap, starting at 0 and
217 * not exceeding size - 1. Return -1 if not found.
220 fd_last_used(struct filedesc *fdp, int size)
222 NDSLOTTYPE *map = fdp->fd_map;
227 if (size % NDENTRIES) {
228 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
229 if ((mask &= map[off]) != 0)
230 return (off * NDENTRIES + flsl(mask) - 1);
233 for (minoff = NDSLOT(0); off >= minoff; --off)
235 return (off * NDENTRIES + flsl(map[off]) - 1);
240 fdisused(struct filedesc *fdp, int fd)
243 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
244 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
246 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
250 * Mark a file descriptor as used.
253 fdused_init(struct filedesc *fdp, int fd)
256 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
258 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
262 fdused(struct filedesc *fdp, int fd)
265 FILEDESC_XLOCK_ASSERT(fdp);
267 fdused_init(fdp, fd);
268 if (fd > fdp->fd_lastfile)
269 fdp->fd_lastfile = fd;
270 if (fd == fdp->fd_freefile)
275 * Mark a file descriptor as unused.
278 fdunused(struct filedesc *fdp, int fd)
281 FILEDESC_XLOCK_ASSERT(fdp);
283 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
284 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
285 ("fd=%d is still in use", fd));
287 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288 if (fd < fdp->fd_freefile)
289 fdp->fd_freefile = fd;
290 if (fd == fdp->fd_lastfile)
291 fdp->fd_lastfile = fd_last_used(fdp, fd);
295 * Free a file descriptor.
297 * Avoid some work if fdp is about to be destroyed.
300 fdefree_last(struct filedescent *fde)
303 filecaps_free(&fde->fde_caps);
307 fdfree(struct filedesc *fdp, int fd)
309 struct filedescent *fde;
311 fde = &fdp->fd_ofiles[fd];
313 seqc_write_begin(&fde->fde_seqc);
315 fde->fde_file = NULL;
317 seqc_write_end(&fde->fde_seqc);
324 * System calls on descriptors.
326 #ifndef _SYS_SYSPROTO_H_
327 struct getdtablesize_args {
333 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
339 td->td_retval[0] = getmaxfd(td);
341 PROC_LOCK(td->td_proc);
342 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
343 PROC_UNLOCK(td->td_proc);
344 if (lim < td->td_retval[0])
345 td->td_retval[0] = lim;
351 * Duplicate a file descriptor to a particular value.
353 * Note: keep in mind that a potential race condition exists when closing
354 * descriptors from a shared descriptor table (via rfork).
356 #ifndef _SYS_SYSPROTO_H_
364 sys_dup2(struct thread *td, struct dup2_args *uap)
367 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
371 * Duplicate a file descriptor.
373 #ifndef _SYS_SYSPROTO_H_
380 sys_dup(struct thread *td, struct dup_args *uap)
383 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
387 * The file control system call.
389 #ifndef _SYS_SYSPROTO_H_
398 sys_fcntl(struct thread *td, struct fcntl_args *uap)
401 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
405 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
419 * Convert old flock structure to new.
421 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
422 fl.l_start = ofl.l_start;
423 fl.l_len = ofl.l_len;
424 fl.l_pid = ofl.l_pid;
425 fl.l_type = ofl.l_type;
426 fl.l_whence = ofl.l_whence;
440 arg1 = (intptr_t)&fl;
446 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
447 arg1 = (intptr_t)&fl;
455 error = kern_fcntl(td, fd, newcmd, arg1);
458 if (cmd == F_OGETLK) {
459 ofl.l_start = fl.l_start;
460 ofl.l_len = fl.l_len;
461 ofl.l_pid = fl.l_pid;
462 ofl.l_type = fl.l_type;
463 ofl.l_whence = fl.l_whence;
464 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
465 } else if (cmd == F_GETLK) {
466 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
472 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
474 struct filedesc *fdp;
476 struct file *fp, *fp2;
477 struct filedescent *fde;
481 int error, flg, seals, tmp;
495 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
498 case F_DUPFD_CLOEXEC:
500 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
505 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
508 case F_DUP2FD_CLOEXEC:
510 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
516 fde = fdeget_locked(fdp, fd);
519 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
522 FILEDESC_SUNLOCK(fdp);
528 fde = fdeget_locked(fdp, fd);
530 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
531 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
534 FILEDESC_XUNLOCK(fdp);
538 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
541 td->td_retval[0] = OFLAGS(fp->f_flag);
546 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
550 tmp = flg = fp->f_flag;
552 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
553 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
554 tmp = fp->f_flag & FNONBLOCK;
555 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
560 tmp = fp->f_flag & FASYNC;
561 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
566 atomic_clear_int(&fp->f_flag, FNONBLOCK);
568 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
573 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
576 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
578 td->td_retval[0] = tmp;
583 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
587 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
592 error = priv_check(td, PRIV_NFS_LOCKD);
600 /* FALLTHROUGH F_SETLK */
604 flp = (struct flock *)arg;
605 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
610 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
613 if (fp->f_type != DTYPE_VNODE) {
619 if (flp->l_whence == SEEK_CUR) {
620 foffset = foffset_get(fp);
623 foffset > OFF_MAX - flp->l_start)) {
628 flp->l_start += foffset;
632 switch (flp->l_type) {
634 if ((fp->f_flag & FREAD) == 0) {
638 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
639 PROC_LOCK(p->p_leader);
640 p->p_leader->p_flag |= P_ADVLOCK;
641 PROC_UNLOCK(p->p_leader);
643 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
647 if ((fp->f_flag & FWRITE) == 0) {
651 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
652 PROC_LOCK(p->p_leader);
653 p->p_leader->p_flag |= P_ADVLOCK;
654 PROC_UNLOCK(p->p_leader);
656 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
664 if (flg != F_REMOTE) {
668 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
669 F_UNLCKSYS, flp, flg);
675 if (error != 0 || flp->l_type == F_UNLCK ||
676 flp->l_type == F_UNLCKSYS) {
682 * Check for a race with close.
684 * The vnode is now advisory locked (or unlocked, but this case
685 * is not really important) as the caller requested.
686 * We had to drop the filedesc lock, so we need to recheck if
687 * the descriptor is still valid, because if it was closed
688 * in the meantime we need to remove advisory lock from the
689 * vnode - close on any descriptor leading to an advisory
690 * locked vnode, removes that lock.
691 * We will return 0 on purpose in that case, as the result of
692 * successful advisory lock might have been externally visible
693 * already. This is fine - effectively we pretend to the caller
694 * that the closing thread was a bit slower and that the
695 * advisory lock succeeded before the close.
697 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
703 flp->l_whence = SEEK_SET;
706 flp->l_type = F_UNLCK;
707 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708 F_UNLCK, flp, F_POSIX);
715 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
718 if (fp->f_type != DTYPE_VNODE) {
723 flp = (struct flock *)arg;
724 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
725 flp->l_type != F_UNLCK) {
730 if (flp->l_whence == SEEK_CUR) {
731 foffset = foffset_get(fp);
732 if ((flp->l_start > 0 &&
733 foffset > OFF_MAX - flp->l_start) ||
735 foffset < OFF_MIN - flp->l_start)) {
740 flp->l_start += foffset;
743 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
749 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
752 error = fo_add_seals(fp, arg);
757 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
760 if (fo_get_seals(fp, &seals) == 0)
761 td->td_retval[0] = seals;
768 arg = arg ? 128 * 1024: 0;
771 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
774 if (fp->f_type != DTYPE_VNODE) {
780 if (vp->v_type != VREG) {
787 * Exclusive lock synchronizes against f_seqcount reads and
788 * writes in sequential_heuristic().
790 error = vn_lock(vp, LK_EXCLUSIVE);
796 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
797 arg = MIN(arg, INT_MAX - bsize + 1);
798 fp->f_seqcount = MIN(IO_SEQMAX,
799 (arg + bsize - 1) / bsize);
800 atomic_set_int(&fp->f_flag, FRDAHEAD);
802 atomic_clear_int(&fp->f_flag, FRDAHEAD);
810 * Check if the vnode is part of a union stack (either the
811 * "union" flag from mount(2) or unionfs).
813 * Prior to introduction of this op libc's readdir would call
814 * fstatfs(2), in effect unnecessarily copying kilobytes of
815 * data just to check fs name and a mount flag.
817 * Fixing the code to handle everything in the kernel instead
818 * is a non-trivial endeavor and has low priority, thus this
819 * horrible kludge facilitates the current behavior in a much
820 * cheaper manner until someone(tm) sorts this out.
822 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
825 if (fp->f_type != DTYPE_VNODE) {
832 * Since we don't prevent dooming the vnode even non-null mp
833 * found can become immediately stale. This is tolerable since
834 * mount points are type-stable (providing safe memory access)
835 * and any vfs op on this vnode going forward will return an
836 * error (meaning return value in this case is meaningless).
838 mp = atomic_load_ptr(&vp->v_mount);
839 if (__predict_false(mp == NULL)) {
844 td->td_retval[0] = 0;
845 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
846 mp->mnt_flag & MNT_UNION)
847 td->td_retval[0] = 1;
859 getmaxfd(struct thread *td)
862 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
866 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
869 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
871 struct filedesc *fdp;
872 struct filedescent *oldfde, *newfde;
875 u_long *oioctls, *nioctls;
882 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
883 MPASS(mode < FDDUP_LASTMODE);
886 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
889 * Verify we have a valid descriptor to dup from and possibly to
890 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
891 * return EINVAL when the new descriptor is out of bounds.
896 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
897 maxfd = getmaxfd(td);
899 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
903 if (fget_locked(fdp, old) == NULL)
905 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
906 td->td_retval[0] = new;
907 if (flags & FDDUP_FLAG_CLOEXEC)
908 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
913 oldfde = &fdp->fd_ofiles[old];
914 if (!fhold(oldfde->fde_file))
918 * If the caller specified a file descriptor, make sure the file
919 * table is large enough to hold it, and grab it. Otherwise, just
920 * allocate a new descriptor the usual way.
925 if ((error = fdalloc(td, new, &new)) != 0) {
926 fdrop(oldfde->fde_file, td);
930 case FDDUP_MUSTREPLACE:
931 /* Target file descriptor must exist. */
932 if (fget_locked(fdp, new) == NULL) {
933 fdrop(oldfde->fde_file, td);
938 if (new >= fdp->fd_nfiles) {
940 * The resource limits are here instead of e.g.
941 * fdalloc(), because the file descriptor table may be
942 * shared between processes, so we can't really use
943 * racct_add()/racct_sub(). Instead of counting the
944 * number of actually allocated descriptors, just put
945 * the limit on the size of the file descriptor table.
948 if (RACCT_ENABLED()) {
949 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
952 fdrop(oldfde->fde_file, td);
957 fdgrowtable_exp(fdp, new + 1);
959 if (!fdisused(fdp, new))
963 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
966 KASSERT(old != new, ("new fd is same as old"));
968 newfde = &fdp->fd_ofiles[new];
969 delfp = newfde->fde_file;
971 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
974 * Duplicate the source descriptor.
977 seqc_write_begin(&newfde->fde_seqc);
979 oioctls = filecaps_free_prep(&newfde->fde_caps);
980 memcpy(newfde, oldfde, fde_change_size);
981 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
983 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
984 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
986 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
988 seqc_write_end(&newfde->fde_seqc);
990 td->td_retval[0] = new;
995 (void) closefp(fdp, new, delfp, td, 1);
996 FILEDESC_UNLOCK_ASSERT(fdp);
999 FILEDESC_XUNLOCK(fdp);
1002 filecaps_free_finish(oioctls);
1007 * If sigio is on the list associated with a process or process group,
1008 * disable signalling from the device, remove sigio from the list and
1012 funsetown(struct sigio **sigiop)
1014 struct sigio *sigio;
1016 if (*sigiop == NULL)
1020 if (sigio == NULL) {
1024 *(sigio->sio_myref) = NULL;
1025 if ((sigio)->sio_pgid < 0) {
1026 struct pgrp *pg = (sigio)->sio_pgrp;
1028 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1029 sigio, sio_pgsigio);
1032 struct proc *p = (sigio)->sio_proc;
1034 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1035 sigio, sio_pgsigio);
1039 crfree(sigio->sio_ucred);
1040 free(sigio, M_SIGIO);
1044 * Free a list of sigio structures.
1045 * We only need to lock the SIGIO_LOCK because we have made ourselves
1046 * inaccessible to callers of fsetown and therefore do not need to lock
1047 * the proc or pgrp struct for the list manipulation.
1050 funsetownlst(struct sigiolst *sigiolst)
1054 struct sigio *sigio;
1056 sigio = SLIST_FIRST(sigiolst);
1063 * Every entry of the list should belong
1064 * to a single proc or pgrp.
1066 if (sigio->sio_pgid < 0) {
1067 pg = sigio->sio_pgrp;
1068 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1069 } else /* if (sigio->sio_pgid > 0) */ {
1070 p = sigio->sio_proc;
1071 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1075 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1076 *(sigio->sio_myref) = NULL;
1078 KASSERT(sigio->sio_pgid < 0,
1079 ("Proc sigio in pgrp sigio list"));
1080 KASSERT(sigio->sio_pgrp == pg,
1081 ("Bogus pgrp in sigio list"));
1083 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1086 } else /* if (p != NULL) */ {
1087 KASSERT(sigio->sio_pgid > 0,
1088 ("Pgrp sigio in proc sigio list"));
1089 KASSERT(sigio->sio_proc == p,
1090 ("Bogus proc in sigio list"));
1092 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1097 crfree(sigio->sio_ucred);
1098 free(sigio, M_SIGIO);
1105 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1107 * After permission checking, add a sigio structure to the sigio list for
1108 * the process or process group.
1111 fsetown(pid_t pgid, struct sigio **sigiop)
1115 struct sigio *sigio;
1125 /* Allocate and fill in the new sigio out of locks. */
1126 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1127 sigio->sio_pgid = pgid;
1128 sigio->sio_ucred = crhold(curthread->td_ucred);
1129 sigio->sio_myref = sigiop;
1131 sx_slock(&proctree_lock);
1140 * Policy - Don't allow a process to FSETOWN a process
1141 * in another session.
1143 * Remove this test to allow maximum flexibility or
1144 * restrict FSETOWN to the current process or process
1145 * group for maximum safety.
1148 if (proc->p_session != curthread->td_proc->p_session) {
1154 } else /* if (pgid < 0) */ {
1155 pgrp = pgfind(-pgid);
1163 * Policy - Don't allow a process to FSETOWN a process
1164 * in another session.
1166 * Remove this test to allow maximum flexibility or
1167 * restrict FSETOWN to the current process or process
1168 * group for maximum safety.
1170 if (pgrp->pg_session != curthread->td_proc->p_session) {
1181 * Since funsetownlst() is called without the proctree
1182 * locked, we need to check for P_WEXIT.
1183 * XXX: is ESRCH correct?
1185 if ((proc->p_flag & P_WEXIT) != 0) {
1190 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1191 sigio->sio_proc = proc;
1195 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1196 sigio->sio_pgrp = pgrp;
1199 sx_sunlock(&proctree_lock);
1206 sx_sunlock(&proctree_lock);
1207 crfree(sigio->sio_ucred);
1208 free(sigio, M_SIGIO);
1213 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1216 fgetown(struct sigio **sigiop)
1221 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1227 * Function drops the filedesc lock on return.
1230 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1235 FILEDESC_XLOCK_ASSERT(fdp);
1238 if (td->td_proc->p_fdtol != NULL) {
1240 * Ask fdfree() to sleep to ensure that all relevant
1241 * process leaders can be traversed in closef().
1243 fdp->fd_holdleaderscount++;
1250 * We now hold the fp reference that used to be owned by the
1251 * descriptor array. We have to unlock the FILEDESC *AFTER*
1252 * knote_fdclose to prevent a race of the fd getting opened, a knote
1253 * added, and deleteing a knote for the new fd.
1255 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1256 knote_fdclose(td, fd);
1259 * We need to notify mqueue if the object is of type mqueue.
1261 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1262 mq_fdclose(td, fd, fp);
1263 FILEDESC_XUNLOCK(fdp);
1265 error = closef(fp, td);
1267 FILEDESC_XLOCK(fdp);
1268 fdp->fd_holdleaderscount--;
1269 if (fdp->fd_holdleaderscount == 0 &&
1270 fdp->fd_holdleaderswakeup != 0) {
1271 fdp->fd_holdleaderswakeup = 0;
1272 wakeup(&fdp->fd_holdleaderscount);
1274 FILEDESC_XUNLOCK(fdp);
1280 * Close a file descriptor.
1282 #ifndef _SYS_SYSPROTO_H_
1289 sys_close(struct thread *td, struct close_args *uap)
1292 return (kern_close(td, uap->fd));
1296 kern_close(struct thread *td, int fd)
1298 struct filedesc *fdp;
1301 fdp = td->td_proc->p_fd;
1303 AUDIT_SYSCLOSE(td, fd);
1305 FILEDESC_XLOCK(fdp);
1306 if ((fp = fget_locked(fdp, fd)) == NULL) {
1307 FILEDESC_XUNLOCK(fdp);
1312 /* closefp() drops the FILEDESC lock for us. */
1313 return (closefp(fdp, fd, fp, td, 1));
1317 kern_close_range(struct thread *td, u_int lowfd, u_int highfd)
1319 struct filedesc *fdp;
1323 fdp = td->td_proc->p_fd;
1324 FILEDESC_SLOCK(fdp);
1327 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1328 * open should not be a usage error. From a close_range() perspective,
1329 * close_range(3, ~0U, 0) in the same scenario should also likely not
1330 * be a usage error as all fd above 3 are in-fact already closed.
1332 if (highfd < lowfd) {
1338 * If fdp->fd_lastfile == -1, we're dealing with either a fresh file
1339 * table or one in which every fd has been closed. Just return
1340 * successful; there's nothing left to do.
1342 if (fdp->fd_lastfile == -1)
1344 /* Clamped to [lowfd, fd_lastfile] */
1345 highfd = MIN(highfd, fdp->fd_lastfile);
1346 for (fd = lowfd; fd <= highfd; fd++) {
1347 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1348 FILEDESC_SUNLOCK(fdp);
1349 (void)kern_close(td, fd);
1350 FILEDESC_SLOCK(fdp);
1354 FILEDESC_SUNLOCK(fdp);
1358 #ifndef _SYS_SYSPROTO_H_
1359 struct close_range_args {
1366 sys_close_range(struct thread *td, struct close_range_args *uap)
1369 /* No flags currently defined */
1370 if (uap->flags != 0)
1372 return (kern_close_range(td, uap->lowfd, uap->highfd));
1375 #ifdef COMPAT_FREEBSD12
1377 * Close open file descriptors.
1379 #ifndef _SYS_SYSPROTO_H_
1380 struct freebsd12_closefrom_args {
1386 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1390 AUDIT_ARG_FD(uap->lowfd);
1393 * Treat negative starting file descriptor values identical to
1394 * closefrom(0) which closes all files.
1396 lowfd = MAX(0, uap->lowfd);
1397 return (kern_close_range(td, lowfd, ~0U));
1399 #endif /* COMPAT_FREEBSD12 */
1401 #if defined(COMPAT_43)
1403 * Return status information about a file descriptor.
1405 #ifndef _SYS_SYSPROTO_H_
1406 struct ofstat_args {
1413 ofstat(struct thread *td, struct ofstat_args *uap)
1419 error = kern_fstat(td, uap->fd, &ub);
1422 error = copyout(&oub, uap->sb, sizeof(oub));
1426 #endif /* COMPAT_43 */
1428 #if defined(COMPAT_FREEBSD11)
1430 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1433 struct freebsd11_stat osb;
1436 error = kern_fstat(td, uap->fd, &sb);
1439 error = freebsd11_cvtstat(&sb, &osb);
1441 error = copyout(&osb, uap->sb, sizeof(osb));
1444 #endif /* COMPAT_FREEBSD11 */
1447 * Return status information about a file descriptor.
1449 #ifndef _SYS_SYSPROTO_H_
1457 sys_fstat(struct thread *td, struct fstat_args *uap)
1462 error = kern_fstat(td, uap->fd, &ub);
1464 error = copyout(&ub, uap->sb, sizeof(ub));
1469 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1476 error = fget(td, fd, &cap_fstat_rights, &fp);
1477 if (__predict_false(error != 0))
1480 AUDIT_ARG_FILE(td->td_proc, fp);
1482 error = fo_stat(fp, sbp, td->td_ucred, td);
1484 #ifdef __STAT_TIME_T_EXT
1485 sbp->st_atim_ext = 0;
1486 sbp->st_mtim_ext = 0;
1487 sbp->st_ctim_ext = 0;
1488 sbp->st_btim_ext = 0;
1491 if (KTRPOINT(td, KTR_STRUCT))
1492 ktrstat_error(sbp, error);
1497 #if defined(COMPAT_FREEBSD11)
1499 * Return status information about a file descriptor.
1501 #ifndef _SYS_SYSPROTO_H_
1502 struct freebsd11_nfstat_args {
1509 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1515 error = kern_fstat(td, uap->fd, &ub);
1517 freebsd11_cvtnstat(&ub, &nub);
1518 error = copyout(&nub, uap->sb, sizeof(nub));
1522 #endif /* COMPAT_FREEBSD11 */
1525 * Return pathconf information about a file descriptor.
1527 #ifndef _SYS_SYSPROTO_H_
1528 struct fpathconf_args {
1535 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1540 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1542 td->td_retval[0] = value;
1547 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1553 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1557 if (name == _PC_ASYNC_IO) {
1558 *valuep = _POSIX_ASYNCHRONOUS_IO;
1563 vn_lock(vp, LK_SHARED | LK_RETRY);
1564 error = VOP_PATHCONF(vp, name, valuep);
1566 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1567 if (name != _PC_PIPE_BUF) {
1582 * Copy filecaps structure allocating memory for ioctls array if needed.
1584 * The last parameter indicates whether the fdtable is locked. If it is not and
1585 * ioctls are encountered, copying fails and the caller must lock the table.
1587 * Note that if the table was not locked, the caller has to check the relevant
1588 * sequence counter to determine whether the operation was successful.
1591 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1595 if (src->fc_ioctls != NULL && !locked)
1597 memcpy(dst, src, sizeof(*src));
1598 if (src->fc_ioctls == NULL)
1601 KASSERT(src->fc_nioctls > 0,
1602 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1604 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1605 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1606 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1611 filecaps_copy_prep(const struct filecaps *src)
1616 if (__predict_true(src->fc_ioctls == NULL))
1619 KASSERT(src->fc_nioctls > 0,
1620 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1622 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1623 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1628 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1634 if (__predict_true(src->fc_ioctls == NULL)) {
1635 MPASS(ioctls == NULL);
1639 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1640 dst->fc_ioctls = ioctls;
1641 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1645 * Move filecaps structure to the new place and clear the old place.
1648 filecaps_move(struct filecaps *src, struct filecaps *dst)
1652 bzero(src, sizeof(*src));
1656 * Fill the given filecaps structure with full rights.
1659 filecaps_fill(struct filecaps *fcaps)
1662 CAP_ALL(&fcaps->fc_rights);
1663 fcaps->fc_ioctls = NULL;
1664 fcaps->fc_nioctls = -1;
1665 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1669 * Free memory allocated within filecaps structure.
1672 filecaps_free(struct filecaps *fcaps)
1675 free(fcaps->fc_ioctls, M_FILECAPS);
1676 bzero(fcaps, sizeof(*fcaps));
1680 filecaps_free_prep(struct filecaps *fcaps)
1684 ioctls = fcaps->fc_ioctls;
1685 bzero(fcaps, sizeof(*fcaps));
1690 filecaps_free_finish(u_long *ioctls)
1693 free(ioctls, M_FILECAPS);
1697 * Validate the given filecaps structure.
1700 filecaps_validate(const struct filecaps *fcaps, const char *func)
1703 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1704 ("%s: invalid rights", func));
1705 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1706 ("%s: invalid fcntls", func));
1707 KASSERT(fcaps->fc_fcntls == 0 ||
1708 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1709 ("%s: fcntls without CAP_FCNTL", func));
1710 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1711 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1712 ("%s: invalid ioctls", func));
1713 KASSERT(fcaps->fc_nioctls == 0 ||
1714 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1715 ("%s: ioctls without CAP_IOCTL", func));
1719 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1723 FILEDESC_XLOCK_ASSERT(fdp);
1725 nfd1 = fdp->fd_nfiles * 2;
1728 fdgrowtable(fdp, nfd1);
1732 * Grow the file table to accommodate (at least) nfd descriptors.
1735 fdgrowtable(struct filedesc *fdp, int nfd)
1737 struct filedesc0 *fdp0;
1738 struct freetable *ft;
1739 struct fdescenttbl *ntable;
1740 struct fdescenttbl *otable;
1741 int nnfiles, onfiles;
1742 NDSLOTTYPE *nmap, *omap;
1745 * If lastfile is -1 this struct filedesc was just allocated and we are
1746 * growing it to accommodate for the one we are going to copy from. There
1747 * is no need to have a lock on this one as it's not visible to anyone.
1749 if (fdp->fd_lastfile != -1)
1750 FILEDESC_XLOCK_ASSERT(fdp);
1752 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1754 /* save old values */
1755 onfiles = fdp->fd_nfiles;
1756 otable = fdp->fd_files;
1759 /* compute the size of the new table */
1760 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1761 if (nnfiles <= onfiles)
1762 /* the table is already large enough */
1766 * Allocate a new table. We need enough space for the number of
1767 * entries, file entries themselves and the struct freetable we will use
1768 * when we decommission the table and place it on the freelist.
1769 * We place the struct freetable in the middle so we don't have
1770 * to worry about padding.
1772 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1773 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1774 sizeof(struct freetable),
1775 M_FILEDESC, M_ZERO | M_WAITOK);
1776 /* copy the old data */
1777 ntable->fdt_nfiles = nnfiles;
1778 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1779 onfiles * sizeof(ntable->fdt_ofiles[0]));
1782 * Allocate a new map only if the old is not large enough. It will
1783 * grow at a slower rate than the table as it can map more
1784 * entries than the table can hold.
1786 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1787 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1789 /* copy over the old data and update the pointer */
1790 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1795 * Make sure that ntable is correctly initialized before we replace
1796 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1799 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1802 * Do not free the old file table, as some threads may still
1803 * reference entries within it. Instead, place it on a freelist
1804 * which will be processed when the struct filedesc is released.
1806 * Note that if onfiles == NDFILE, we're dealing with the original
1807 * static allocation contained within (struct filedesc0 *)fdp,
1808 * which must not be freed.
1810 if (onfiles > NDFILE) {
1811 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1812 fdp0 = (struct filedesc0 *)fdp;
1813 ft->ft_table = otable;
1814 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1817 * The map does not have the same possibility of threads still
1818 * holding references to it. So always free it as long as it
1819 * does not reference the original static allocation.
1821 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1822 free(omap, M_FILEDESC);
1826 * Allocate a file descriptor for the process.
1829 fdalloc(struct thread *td, int minfd, int *result)
1831 struct proc *p = td->td_proc;
1832 struct filedesc *fdp = p->p_fd;
1833 int fd, maxfd, allocfd;
1838 FILEDESC_XLOCK_ASSERT(fdp);
1840 if (fdp->fd_freefile > minfd)
1841 minfd = fdp->fd_freefile;
1843 maxfd = getmaxfd(td);
1846 * Search the bitmap for a free descriptor starting at minfd.
1847 * If none is found, grow the file table.
1849 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1852 if (fd >= fdp->fd_nfiles) {
1853 allocfd = min(fd * 2, maxfd);
1855 if (RACCT_ENABLED()) {
1856 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1862 * fd is already equal to first free descriptor >= minfd, so
1863 * we only need to grow the table and we are done.
1865 fdgrowtable_exp(fdp, allocfd);
1869 * Perform some sanity checks, then mark the file descriptor as
1870 * used and return it to the caller.
1872 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1873 ("invalid descriptor %d", fd));
1874 KASSERT(!fdisused(fdp, fd),
1875 ("fd_first_free() returned non-free descriptor"));
1876 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1877 ("file descriptor isn't free"));
1884 * Allocate n file descriptors for the process.
1887 fdallocn(struct thread *td, int minfd, int *fds, int n)
1889 struct proc *p = td->td_proc;
1890 struct filedesc *fdp = p->p_fd;
1893 FILEDESC_XLOCK_ASSERT(fdp);
1895 for (i = 0; i < n; i++)
1896 if (fdalloc(td, 0, &fds[i]) != 0)
1900 for (i--; i >= 0; i--)
1901 fdunused(fdp, fds[i]);
1909 * Create a new open file structure and allocate a file descriptor for the
1910 * process that refers to it. We add one reference to the file for the
1911 * descriptor table and one reference for resultfp. This is to prevent us
1912 * being preempted and the entry in the descriptor table closed after we
1913 * release the FILEDESC lock.
1916 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1917 struct filecaps *fcaps)
1922 error = falloc_noinstall(td, &fp);
1924 return (error); /* no reference held on error */
1926 error = finstall(td, fp, &fd, flags, fcaps);
1928 fdrop(fp, td); /* one reference (fp only) */
1932 if (resultfp != NULL)
1933 *resultfp = fp; /* copy out result */
1935 fdrop(fp, td); /* release local reference */
1937 if (resultfd != NULL)
1944 * Create a new open file structure without allocating a file descriptor.
1947 falloc_noinstall(struct thread *td, struct file **resultfp)
1950 int maxuserfiles = maxfiles - (maxfiles / 20);
1952 static struct timeval lastfail;
1955 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1957 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1958 if ((openfiles_new >= maxuserfiles &&
1959 priv_check(td, PRIV_MAXFILES) != 0) ||
1960 openfiles_new >= maxfiles) {
1961 atomic_subtract_int(&openfiles, 1);
1962 if (ppsratecheck(&lastfail, &curfail, 1)) {
1963 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1964 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1968 fp = uma_zalloc(file_zone, M_WAITOK);
1969 bzero(fp, sizeof(*fp));
1970 refcount_init(&fp->f_count, 1);
1971 fp->f_cred = crhold(td->td_ucred);
1972 fp->f_ops = &badfileops;
1978 * Install a file in a file descriptor table.
1981 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1982 struct filecaps *fcaps)
1984 struct filedescent *fde;
1988 filecaps_validate(fcaps, __func__);
1989 FILEDESC_XLOCK_ASSERT(fdp);
1991 fde = &fdp->fd_ofiles[fd];
1993 seqc_write_begin(&fde->fde_seqc);
1996 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1998 filecaps_move(fcaps, &fde->fde_caps);
2000 filecaps_fill(&fde->fde_caps);
2002 seqc_write_end(&fde->fde_seqc);
2007 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2008 struct filecaps *fcaps)
2010 struct filedesc *fdp = td->td_proc->p_fd;
2017 FILEDESC_XLOCK(fdp);
2018 error = fdalloc(td, 0, fd);
2019 if (__predict_false(error != 0)) {
2020 FILEDESC_XUNLOCK(fdp);
2024 _finstall(fdp, fp, *fd, flags, fcaps);
2025 FILEDESC_XUNLOCK(fdp);
2030 * Build a new filedesc structure from another.
2031 * Copy the current, root, and jail root vnode references.
2033 * If fdp is not NULL, return with it shared locked.
2036 fdinit(struct filedesc *fdp, bool prepfiles)
2038 struct filedesc0 *newfdp0;
2039 struct filedesc *newfdp;
2042 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2043 newfdp = &newfdp0->fd_fd;
2045 /* Create the file descriptor table. */
2046 FILEDESC_LOCK_INIT(newfdp);
2047 refcount_init(&newfdp->fd_refcnt, 1);
2048 refcount_init(&newfdp->fd_holdcnt, 1);
2049 newfdp->fd_cmask = CMASK;
2050 newfdp->fd_map = newfdp0->fd_dmap;
2051 newfdp->fd_lastfile = -1;
2052 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2053 newfdp->fd_files->fdt_nfiles = NDFILE;
2056 newpwd = pwd_alloc();
2057 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2061 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2062 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2064 FILEDESC_SLOCK(fdp);
2065 newpwd = pwd_hold_filedesc(fdp);
2066 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2069 FILEDESC_SUNLOCK(fdp);
2071 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2072 FILEDESC_SUNLOCK(fdp);
2073 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2074 FILEDESC_SLOCK(fdp);
2081 static struct filedesc *
2082 fdhold(struct proc *p)
2084 struct filedesc *fdp;
2086 PROC_LOCK_ASSERT(p, MA_OWNED);
2089 refcount_acquire(&fdp->fd_holdcnt);
2094 fddrop(struct filedesc *fdp)
2097 if (fdp->fd_holdcnt > 1) {
2098 if (refcount_release(&fdp->fd_holdcnt) == 0)
2102 FILEDESC_LOCK_DESTROY(fdp);
2103 uma_zfree(filedesc0_zone, fdp);
2107 * Share a filedesc structure.
2110 fdshare(struct filedesc *fdp)
2113 refcount_acquire(&fdp->fd_refcnt);
2118 * Unshare a filedesc structure, if necessary by making a copy
2121 fdunshare(struct thread *td)
2123 struct filedesc *tmp;
2124 struct proc *p = td->td_proc;
2126 if (p->p_fd->fd_refcnt == 1)
2129 tmp = fdcopy(p->p_fd);
2135 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2139 td->td_proc->p_fd = fdp;
2143 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2144 * this is to ease callers, not catch errors.
2147 fdcopy(struct filedesc *fdp)
2149 struct filedesc *newfdp;
2150 struct filedescent *nfde, *ofde;
2155 newfdp = fdinit(fdp, true);
2156 /* copy all passable descriptors (i.e. not kqueue) */
2157 newfdp->fd_freefile = -1;
2158 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2159 ofde = &fdp->fd_ofiles[i];
2160 if (ofde->fde_file == NULL ||
2161 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2162 !fhold(ofde->fde_file)) {
2163 if (newfdp->fd_freefile == -1)
2164 newfdp->fd_freefile = i;
2167 nfde = &newfdp->fd_ofiles[i];
2169 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2170 fdused_init(newfdp, i);
2171 newfdp->fd_lastfile = i;
2173 if (newfdp->fd_freefile == -1)
2174 newfdp->fd_freefile = i;
2175 newfdp->fd_cmask = fdp->fd_cmask;
2176 FILEDESC_SUNLOCK(fdp);
2181 * Copies a filedesc structure, while remapping all file descriptors
2182 * stored inside using a translation table.
2184 * File descriptors are copied over to the new file descriptor table,
2185 * regardless of whether the close-on-exec flag is set.
2188 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2189 struct filedesc **ret)
2191 struct filedesc *newfdp;
2192 struct filedescent *nfde, *ofde;
2197 newfdp = fdinit(fdp, true);
2198 if (nfds > fdp->fd_lastfile + 1) {
2199 /* New table cannot be larger than the old one. */
2203 /* Copy all passable descriptors (i.e. not kqueue). */
2204 newfdp->fd_freefile = nfds;
2205 for (i = 0; i < nfds; ++i) {
2206 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2207 /* File descriptor out of bounds. */
2211 ofde = &fdp->fd_ofiles[fds[i]];
2212 if (ofde->fde_file == NULL) {
2213 /* Unused file descriptor. */
2217 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2218 /* File descriptor cannot be passed. */
2222 if (!fhold(nfde->fde_file)) {
2226 nfde = &newfdp->fd_ofiles[i];
2228 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2229 fdused_init(newfdp, i);
2230 newfdp->fd_lastfile = i;
2232 newfdp->fd_cmask = fdp->fd_cmask;
2233 FILEDESC_SUNLOCK(fdp);
2237 FILEDESC_SUNLOCK(fdp);
2238 fdescfree_remapped(newfdp);
2243 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2244 * one of processes using it exits) and the table used to be shared.
2247 fdclearlocks(struct thread *td)
2249 struct filedesc *fdp;
2250 struct filedesc_to_leader *fdtol;
2260 MPASS(fdtol != NULL);
2262 FILEDESC_XLOCK(fdp);
2263 KASSERT(fdtol->fdl_refcount > 0,
2264 ("filedesc_to_refcount botch: fdl_refcount=%d",
2265 fdtol->fdl_refcount));
2266 if (fdtol->fdl_refcount == 1 &&
2267 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2268 for (i = 0; i <= fdp->fd_lastfile; i++) {
2269 fp = fdp->fd_ofiles[i].fde_file;
2270 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2273 FILEDESC_XUNLOCK(fdp);
2274 lf.l_whence = SEEK_SET;
2277 lf.l_type = F_UNLCK;
2279 (void) VOP_ADVLOCK(vp,
2280 (caddr_t)p->p_leader, F_UNLCK,
2282 FILEDESC_XLOCK(fdp);
2287 if (fdtol->fdl_refcount == 1) {
2288 if (fdp->fd_holdleaderscount > 0 &&
2289 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2291 * close() or kern_dup() has cleared a reference
2292 * in a shared file descriptor table.
2294 fdp->fd_holdleaderswakeup = 1;
2295 sx_sleep(&fdp->fd_holdleaderscount,
2296 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2299 if (fdtol->fdl_holdcount > 0) {
2301 * Ensure that fdtol->fdl_leader remains
2302 * valid in closef().
2304 fdtol->fdl_wakeup = 1;
2305 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2310 fdtol->fdl_refcount--;
2311 if (fdtol->fdl_refcount == 0 &&
2312 fdtol->fdl_holdcount == 0) {
2313 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2314 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2318 FILEDESC_XUNLOCK(fdp);
2320 free(fdtol, M_FILEDESC_TO_LEADER);
2324 * Release a filedesc structure.
2327 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2329 struct filedesc0 *fdp0;
2330 struct freetable *ft, *tft;
2331 struct filedescent *fde;
2335 for (i = 0; i <= fdp->fd_lastfile; i++) {
2336 fde = &fdp->fd_ofiles[i];
2341 (void) closef(fp, td);
2347 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2348 free(fdp->fd_map, M_FILEDESC);
2349 if (fdp->fd_nfiles > NDFILE)
2350 free(fdp->fd_files, M_FILEDESC);
2352 fdp0 = (struct filedesc0 *)fdp;
2353 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2354 free(ft->ft_table, M_FILEDESC);
2360 fdescfree(struct thread *td)
2363 struct filedesc *fdp;
2371 if (RACCT_ENABLED())
2372 racct_set_unlocked(p, RACCT_NOFILE, 0);
2375 if (p->p_fdtol != NULL)
2382 if (refcount_release(&fdp->fd_refcnt) == 0)
2385 FILEDESC_XLOCK(fdp);
2386 pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2388 FILEDESC_XUNLOCK(fdp);
2392 fdescfree_fds(td, fdp, 1);
2396 fdescfree_remapped(struct filedesc *fdp)
2399 pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2400 fdescfree_fds(curthread, fdp, 0);
2404 * For setugid programs, we don't want to people to use that setugidness
2405 * to generate error messages which write to a file which otherwise would
2406 * otherwise be off-limits to the process. We check for filesystems where
2407 * the vnode can change out from under us after execve (like [lin]procfs).
2409 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2410 * sufficient. We also don't check for setugidness since we know we are.
2413 is_unsafe(struct file *fp)
2417 if (fp->f_type != DTYPE_VNODE)
2421 return ((vp->v_vflag & VV_PROCDEP) != 0);
2425 * Make this setguid thing safe, if at all possible.
2428 fdsetugidsafety(struct thread *td)
2430 struct filedesc *fdp;
2434 fdp = td->td_proc->p_fd;
2435 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2436 MPASS(fdp->fd_nfiles >= 3);
2437 for (i = 0; i <= 2; i++) {
2438 fp = fdp->fd_ofiles[i].fde_file;
2439 if (fp != NULL && is_unsafe(fp)) {
2440 FILEDESC_XLOCK(fdp);
2441 knote_fdclose(td, i);
2443 * NULL-out descriptor prior to close to avoid
2444 * a race while close blocks.
2447 FILEDESC_XUNLOCK(fdp);
2448 (void) closef(fp, td);
2454 * If a specific file object occupies a specific file descriptor, close the
2455 * file descriptor entry and drop a reference on the file object. This is a
2456 * convenience function to handle a subsequent error in a function that calls
2457 * falloc() that handles the race that another thread might have closed the
2458 * file descriptor out from under the thread creating the file object.
2461 fdclose(struct thread *td, struct file *fp, int idx)
2463 struct filedesc *fdp = td->td_proc->p_fd;
2465 FILEDESC_XLOCK(fdp);
2466 if (fdp->fd_ofiles[idx].fde_file == fp) {
2468 FILEDESC_XUNLOCK(fdp);
2471 FILEDESC_XUNLOCK(fdp);
2475 * Close any files on exec?
2478 fdcloseexec(struct thread *td)
2480 struct filedesc *fdp;
2481 struct filedescent *fde;
2485 fdp = td->td_proc->p_fd;
2486 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2487 for (i = 0; i <= fdp->fd_lastfile; i++) {
2488 fde = &fdp->fd_ofiles[i];
2490 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2491 (fde->fde_flags & UF_EXCLOSE))) {
2492 FILEDESC_XLOCK(fdp);
2494 (void) closefp(fdp, i, fp, td, 0);
2495 FILEDESC_UNLOCK_ASSERT(fdp);
2501 * It is unsafe for set[ug]id processes to be started with file
2502 * descriptors 0..2 closed, as these descriptors are given implicit
2503 * significance in the Standard C library. fdcheckstd() will create a
2504 * descriptor referencing /dev/null for each of stdin, stdout, and
2505 * stderr that is not already open.
2508 fdcheckstd(struct thread *td)
2510 struct filedesc *fdp;
2512 int i, error, devnull;
2514 fdp = td->td_proc->p_fd;
2515 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2516 MPASS(fdp->fd_nfiles >= 3);
2518 for (i = 0; i <= 2; i++) {
2519 if (fdp->fd_ofiles[i].fde_file != NULL)
2522 save = td->td_retval[0];
2523 if (devnull != -1) {
2524 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2526 error = kern_openat(td, AT_FDCWD, "/dev/null",
2527 UIO_SYSSPACE, O_RDWR, 0);
2529 devnull = td->td_retval[0];
2530 KASSERT(devnull == i, ("we didn't get our fd"));
2533 td->td_retval[0] = save;
2541 * Internal form of close. Decrement reference count on file structure.
2542 * Note: td may be NULL when closing a file that was being passed in a
2546 closef(struct file *fp, struct thread *td)
2550 struct filedesc_to_leader *fdtol;
2551 struct filedesc *fdp;
2554 * POSIX record locking dictates that any close releases ALL
2555 * locks owned by this process. This is handled by setting
2556 * a flag in the unlock to free ONLY locks obeying POSIX
2557 * semantics, and not to free BSD-style file locks.
2558 * If the descriptor was in a message, POSIX-style locks
2559 * aren't passed with the descriptor, and the thread pointer
2560 * will be NULL. Callers should be careful only to pass a
2561 * NULL thread pointer when there really is no owning
2562 * context that might have locks, or the locks will be
2565 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2567 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2568 lf.l_whence = SEEK_SET;
2571 lf.l_type = F_UNLCK;
2572 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2573 F_UNLCK, &lf, F_POSIX);
2575 fdtol = td->td_proc->p_fdtol;
2576 if (fdtol != NULL) {
2578 * Handle special case where file descriptor table is
2579 * shared between multiple process leaders.
2581 fdp = td->td_proc->p_fd;
2582 FILEDESC_XLOCK(fdp);
2583 for (fdtol = fdtol->fdl_next;
2584 fdtol != td->td_proc->p_fdtol;
2585 fdtol = fdtol->fdl_next) {
2586 if ((fdtol->fdl_leader->p_flag &
2589 fdtol->fdl_holdcount++;
2590 FILEDESC_XUNLOCK(fdp);
2591 lf.l_whence = SEEK_SET;
2594 lf.l_type = F_UNLCK;
2596 (void) VOP_ADVLOCK(vp,
2597 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2599 FILEDESC_XLOCK(fdp);
2600 fdtol->fdl_holdcount--;
2601 if (fdtol->fdl_holdcount == 0 &&
2602 fdtol->fdl_wakeup != 0) {
2603 fdtol->fdl_wakeup = 0;
2607 FILEDESC_XUNLOCK(fdp);
2610 return (fdrop(fp, td));
2614 * Initialize the file pointer with the specified properties.
2616 * The ops are set with release semantics to be certain that the flags, type,
2617 * and data are visible when ops is. This is to prevent ops methods from being
2618 * called with bad data.
2621 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2626 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2630 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2631 struct file **fpp, struct filecaps *havecapsp)
2633 struct filedescent *fde;
2636 FILEDESC_LOCK_ASSERT(fdp);
2638 fde = fdeget_locked(fdp, fd);
2645 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2650 if (havecapsp != NULL)
2651 filecaps_copy(&fde->fde_caps, havecapsp, true);
2653 *fpp = fde->fde_file;
2661 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2662 struct file **fpp, struct filecaps *havecapsp)
2664 struct filedesc *fdp = td->td_proc->p_fd;
2666 #ifndef CAPABILITIES
2667 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2668 if (havecapsp != NULL && error == 0)
2669 filecaps_fill(havecapsp);
2676 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2680 if (havecapsp != NULL) {
2681 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2682 havecapsp, false)) {
2688 if (!fd_modified(fdp, fd, seq))
2697 FILEDESC_SLOCK(fdp);
2698 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2699 if (error == 0 && !fhold(*fpp))
2701 FILEDESC_SUNLOCK(fdp);
2707 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2708 struct file **fpp, seqc_t *seqp)
2711 const struct filedescent *fde;
2713 const struct fdescenttbl *fdt;
2717 cap_rights_t haverights;
2721 fdt = fdp->fd_files;
2722 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2725 * Fetch the descriptor locklessly. We avoid fdrop() races by
2726 * never raising a refcount above 0. To accomplish this we have
2727 * to use a cmpset loop rather than an atomic_add. The descriptor
2728 * must be re-verified once we acquire a reference to be certain
2729 * that the identity is still correct and we did not lose a race
2730 * due to preemption.
2734 seq = seqc_read(fd_seqc(fdt, fd));
2735 fde = &fdt->fdt_ofiles[fd];
2736 haverights = *cap_rights_fde_inline(fde);
2738 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2741 fp = fdt->fdt_ofiles[fd].fde_file;
2746 error = cap_check_inline(&haverights, needrightsp);
2750 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2752 * The count was found either saturated or zero.
2753 * This re-read is not any more racy than using the
2754 * return value from fcmpset.
2756 if (fp->f_count != 0)
2759 * Force a reload. Other thread could reallocate the
2760 * table before this fd was closed, so it is possible
2761 * that there is a stale fp pointer in cached version.
2763 fdt = atomic_load_ptr(&fdp->fd_files);
2767 * Use an acquire barrier to force re-reading of fdt so it is
2768 * refreshed for verification.
2770 atomic_thread_fence_acq();
2771 fdt = fdp->fd_files;
2773 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2775 if (fp == fdt->fdt_ofiles[fd].fde_file)
2778 fdrop(fp, curthread);
2790 * See the comments in fget_unlocked_seq for an explanation of how this works.
2792 * This is a simplified variant which bails out to the aforementioned routine
2793 * if anything goes wrong. In practice this only happens when userspace is
2794 * racing with itself.
2797 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2801 const struct filedescent *fde;
2803 const struct fdescenttbl *fdt;
2807 const cap_rights_t *haverights;
2810 fdt = fdp->fd_files;
2811 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2814 seq = seqc_read_any(fd_seqc(fdt, fd));
2815 if (__predict_false(seqc_in_modify(seq)))
2817 fde = &fdt->fdt_ofiles[fd];
2818 haverights = cap_rights_fde_inline(fde);
2821 fp = fdt->fdt_ofiles[fd].fde_file;
2823 if (__predict_false(fp == NULL))
2826 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2829 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2833 * Use an acquire barrier to force re-reading of fdt so it is
2834 * refreshed for verification.
2836 atomic_thread_fence_acq();
2837 fdt = fdp->fd_files;
2839 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2841 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2847 fdrop(fp, curthread);
2849 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2853 * Extract the file pointer associated with the specified descriptor for the
2854 * current user process.
2856 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2859 * File's rights will be checked against the capability rights mask.
2861 * If an error occurred the non-zero error is returned and *fpp is set to
2862 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2863 * responsible for fdrop().
2866 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2867 cap_rights_t *needrightsp)
2869 struct filedesc *fdp;
2874 fdp = td->td_proc->p_fd;
2875 error = fget_unlocked(fdp, fd, needrightsp, &fp);
2876 if (__predict_false(error != 0))
2878 if (__predict_false(fp->f_ops == &badfileops)) {
2884 * FREAD and FWRITE failure return EBADF as per POSIX.
2890 if ((fp->f_flag & flags) == 0)
2894 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2895 ((fp->f_flag & FWRITE) != 0))
2901 KASSERT(0, ("wrong flags"));
2914 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2917 return (_fget(td, fd, fpp, 0, rightsp));
2921 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2925 #ifndef CAPABILITIES
2926 error = _fget(td, fd, fpp, 0, rightsp);
2927 if (maxprotp != NULL)
2928 *maxprotp = VM_PROT_ALL;
2931 cap_rights_t fdrights;
2932 struct filedesc *fdp;
2937 fdp = td->td_proc->p_fd;
2938 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2940 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2941 if (__predict_false(error != 0))
2943 if (__predict_false(fp->f_ops == &badfileops)) {
2947 if (maxprotp != NULL)
2948 fdrights = *cap_rights(fdp, fd);
2949 if (!fd_modified(fdp, fd, seq))
2955 * If requested, convert capability rights to access flags.
2957 if (maxprotp != NULL)
2958 *maxprotp = cap_rights_to_vmprot(&fdrights);
2965 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2968 return (_fget(td, fd, fpp, FREAD, rightsp));
2972 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2975 return (_fget(td, fd, fpp, FWRITE, rightsp));
2979 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2982 struct filedesc *fdp = td->td_proc->p_fd;
2983 #ifndef CAPABILITIES
2984 return (fget_unlocked(fdp, fd, rightsp, fpp));
2991 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2993 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2996 error = cap_fcntl_check(fdp, fd, needfcntl);
2997 if (!fd_modified(fdp, fd, seq))
3011 * Like fget() but loads the underlying vnode, or returns an error if the
3012 * descriptor does not represent a vnode. Note that pipes use vnodes but
3013 * never have VM objects. The returned vnode will be vref()'d.
3015 * XXX: what about the unused flags ?
3018 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3025 error = _fget(td, fd, &fp, flags, needrightsp);
3028 if (fp->f_vnode == NULL) {
3040 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3043 return (_fgetvp(td, fd, 0, rightsp, vpp));
3047 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3048 struct filecaps *havecaps, struct vnode **vpp)
3050 struct filecaps caps;
3054 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3057 if (fp->f_ops == &badfileops) {
3061 if (fp->f_vnode == NULL) {
3073 filecaps_free(&caps);
3079 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3082 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3086 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3089 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3094 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3098 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3103 * Handle the last reference to a file being closed.
3105 * Without the noinline attribute clang keeps inlining the func thorough this
3106 * file when fdrop is used.
3109 _fdrop(struct file *fp, struct thread *td)
3113 if (fp->f_count != 0)
3114 panic("fdrop: count %d", fp->f_count);
3115 error = fo_close(fp, td);
3116 atomic_subtract_int(&openfiles, 1);
3118 free(fp->f_advice, M_FADVISE);
3119 uma_zfree(file_zone, fp);
3125 * Apply an advisory lock on a file descriptor.
3127 * Just attempt to get a record lock of the requested type on the entire file
3128 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3130 #ifndef _SYS_SYSPROTO_H_
3138 sys_flock(struct thread *td, struct flock_args *uap)
3145 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3148 if (fp->f_type != DTYPE_VNODE) {
3150 return (EOPNOTSUPP);
3154 lf.l_whence = SEEK_SET;
3157 if (uap->how & LOCK_UN) {
3158 lf.l_type = F_UNLCK;
3159 atomic_clear_int(&fp->f_flag, FHASLOCK);
3160 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3163 if (uap->how & LOCK_EX)
3164 lf.l_type = F_WRLCK;
3165 else if (uap->how & LOCK_SH)
3166 lf.l_type = F_RDLCK;
3171 atomic_set_int(&fp->f_flag, FHASLOCK);
3172 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3173 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3179 * Duplicate the specified descriptor to a free descriptor.
3182 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3183 int openerror, int *indxp)
3185 struct filedescent *newfde, *oldfde;
3190 KASSERT(openerror == ENODEV || openerror == ENXIO,
3191 ("unexpected error %d in %s", openerror, __func__));
3194 * If the to-be-dup'd fd number is greater than the allowed number
3195 * of file descriptors, or the fd to be dup'd has already been
3196 * closed, then reject.
3198 FILEDESC_XLOCK(fdp);
3199 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3200 FILEDESC_XUNLOCK(fdp);
3204 error = fdalloc(td, 0, &indx);
3206 FILEDESC_XUNLOCK(fdp);
3211 * There are two cases of interest here.
3213 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3215 * For ENXIO steal away the file structure from (dfd) and store it in
3216 * (indx). (dfd) is effectively closed by this operation.
3218 switch (openerror) {
3221 * Check that the mode the file is being opened for is a
3222 * subset of the mode of the existing descriptor.
3224 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3225 fdunused(fdp, indx);
3226 FILEDESC_XUNLOCK(fdp);
3230 fdunused(fdp, indx);
3231 FILEDESC_XUNLOCK(fdp);
3234 newfde = &fdp->fd_ofiles[indx];
3235 oldfde = &fdp->fd_ofiles[dfd];
3236 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3238 seqc_write_begin(&newfde->fde_seqc);
3240 memcpy(newfde, oldfde, fde_change_size);
3241 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3244 seqc_write_end(&newfde->fde_seqc);
3249 * Steal away the file pointer from dfd and stuff it into indx.
3251 newfde = &fdp->fd_ofiles[indx];
3252 oldfde = &fdp->fd_ofiles[dfd];
3254 seqc_write_begin(&newfde->fde_seqc);
3256 memcpy(newfde, oldfde, fde_change_size);
3257 oldfde->fde_file = NULL;
3260 seqc_write_end(&newfde->fde_seqc);
3264 FILEDESC_XUNLOCK(fdp);
3270 * This sysctl determines if we will allow a process to chroot(2) if it
3271 * has a directory open:
3272 * 0: disallowed for all processes.
3273 * 1: allowed for processes that were not already chroot(2)'ed.
3274 * 2: allowed for all processes.
3277 static int chroot_allow_open_directories = 1;
3279 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3280 &chroot_allow_open_directories, 0,
3281 "Allow a process to chroot(2) if it has a directory open");
3284 * Helper function for raised chroot(2) security function: Refuse if
3285 * any filedescriptors are open directories.
3288 chroot_refuse_vdir_fds(struct filedesc *fdp)
3294 FILEDESC_LOCK_ASSERT(fdp);
3296 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3297 fp = fget_locked(fdp, fd);
3300 if (fp->f_type == DTYPE_VNODE) {
3302 if (vp->v_type == VDIR)
3310 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3313 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3314 vrefact(oldpwd->pwd_cdir);
3315 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3318 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3319 vrefact(oldpwd->pwd_rdir);
3320 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3323 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3324 vrefact(oldpwd->pwd_jdir);
3325 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3330 pwd_hold_filedesc(struct filedesc *fdp)
3334 FILEDESC_LOCK_ASSERT(fdp);
3335 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3337 refcount_acquire(&pwd->pwd_refcount);
3342 pwd_hold(struct thread *td)
3344 struct filedesc *fdp;
3347 fdp = td->td_proc->p_fd;
3351 pwd = smr_entered_load(&fdp->fd_pwd, pwd_smr);
3353 if (refcount_acquire_if_not_zero(&pwd->pwd_refcount))
3365 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3366 bzero(pwd, sizeof(*pwd));
3367 refcount_init(&pwd->pwd_refcount, 1);
3372 pwd_drop(struct pwd *pwd)
3375 if (!refcount_release(&pwd->pwd_refcount))
3378 if (pwd->pwd_cdir != NULL)
3379 vrele(pwd->pwd_cdir);
3380 if (pwd->pwd_rdir != NULL)
3381 vrele(pwd->pwd_rdir);
3382 if (pwd->pwd_jdir != NULL)
3383 vrele(pwd->pwd_jdir);
3384 uma_zfree_smr(pwd_zone, pwd);
3388 * Common routine for kern_chroot() and jail_attach(). The caller is
3389 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3390 * authorize this operation.
3393 pwd_chroot(struct thread *td, struct vnode *vp)
3395 struct filedesc *fdp;
3396 struct pwd *newpwd, *oldpwd;
3399 fdp = td->td_proc->p_fd;
3400 newpwd = pwd_alloc();
3401 FILEDESC_XLOCK(fdp);
3402 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3403 if (chroot_allow_open_directories == 0 ||
3404 (chroot_allow_open_directories == 1 &&
3405 oldpwd->pwd_rdir != rootvnode)) {
3406 error = chroot_refuse_vdir_fds(fdp);
3408 FILEDESC_XUNLOCK(fdp);
3415 newpwd->pwd_rdir = vp;
3416 if (oldpwd->pwd_jdir == NULL) {
3418 newpwd->pwd_jdir = vp;
3420 pwd_fill(oldpwd, newpwd);
3421 pwd_set(fdp, newpwd);
3422 FILEDESC_XUNLOCK(fdp);
3428 pwd_chdir(struct thread *td, struct vnode *vp)
3430 struct filedesc *fdp;
3431 struct pwd *newpwd, *oldpwd;
3433 VNPASS(vp->v_usecount > 0, vp);
3435 newpwd = pwd_alloc();
3436 fdp = td->td_proc->p_fd;
3437 FILEDESC_XLOCK(fdp);
3438 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3439 newpwd->pwd_cdir = vp;
3440 pwd_fill(oldpwd, newpwd);
3441 pwd_set(fdp, newpwd);
3442 FILEDESC_XUNLOCK(fdp);
3447 pwd_ensure_dirs(void)
3449 struct filedesc *fdp;
3450 struct pwd *oldpwd, *newpwd;
3452 fdp = curproc->p_fd;
3453 FILEDESC_XLOCK(fdp);
3454 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3455 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3456 FILEDESC_XUNLOCK(fdp);
3459 FILEDESC_XUNLOCK(fdp);
3461 newpwd = pwd_alloc();
3462 FILEDESC_XLOCK(fdp);
3463 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3464 pwd_fill(oldpwd, newpwd);
3465 if (newpwd->pwd_cdir == NULL) {
3467 newpwd->pwd_cdir = rootvnode;
3469 if (newpwd->pwd_rdir == NULL) {
3471 newpwd->pwd_rdir = rootvnode;
3473 pwd_set(fdp, newpwd);
3474 FILEDESC_XUNLOCK(fdp);
3479 pwd_set_rootvnode(void)
3481 struct filedesc *fdp;
3482 struct pwd *oldpwd, *newpwd;
3484 fdp = curproc->p_fd;
3486 newpwd = pwd_alloc();
3487 FILEDESC_XLOCK(fdp);
3488 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3490 newpwd->pwd_cdir = rootvnode;
3492 newpwd->pwd_rdir = rootvnode;
3493 pwd_fill(oldpwd, newpwd);
3494 pwd_set(fdp, newpwd);
3495 FILEDESC_XUNLOCK(fdp);
3500 * Scan all active processes and prisons to see if any of them have a current
3501 * or root directory of `olddp'. If so, replace them with the new mount point.
3504 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3506 struct filedesc *fdp;
3507 struct pwd *newpwd, *oldpwd;
3512 if (vrefcnt(olddp) == 1)
3515 newpwd = pwd_alloc();
3516 sx_slock(&allproc_lock);
3517 FOREACH_PROC_IN_SYSTEM(p) {
3523 FILEDESC_XLOCK(fdp);
3524 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3525 if (oldpwd == NULL ||
3526 (oldpwd->pwd_cdir != olddp &&
3527 oldpwd->pwd_rdir != olddp &&
3528 oldpwd->pwd_jdir != olddp)) {
3529 FILEDESC_XUNLOCK(fdp);
3533 if (oldpwd->pwd_cdir == olddp) {
3535 newpwd->pwd_cdir = newdp;
3537 if (oldpwd->pwd_rdir == olddp) {
3539 newpwd->pwd_rdir = newdp;
3541 if (oldpwd->pwd_jdir == olddp) {
3543 newpwd->pwd_jdir = newdp;
3545 pwd_fill(oldpwd, newpwd);
3546 pwd_set(fdp, newpwd);
3547 FILEDESC_XUNLOCK(fdp);
3550 newpwd = pwd_alloc();
3552 sx_sunlock(&allproc_lock);
3554 if (rootvnode == olddp) {
3559 mtx_lock(&prison0.pr_mtx);
3560 if (prison0.pr_root == olddp) {
3562 prison0.pr_root = newdp;
3565 mtx_unlock(&prison0.pr_mtx);
3566 sx_slock(&allprison_lock);
3567 TAILQ_FOREACH(pr, &allprison, pr_list) {
3568 mtx_lock(&pr->pr_mtx);
3569 if (pr->pr_root == olddp) {
3571 pr->pr_root = newdp;
3574 mtx_unlock(&pr->pr_mtx);
3576 sx_sunlock(&allprison_lock);
3581 struct filedesc_to_leader *
3582 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3584 struct filedesc_to_leader *fdtol;
3586 fdtol = malloc(sizeof(struct filedesc_to_leader),
3587 M_FILEDESC_TO_LEADER, M_WAITOK);
3588 fdtol->fdl_refcount = 1;
3589 fdtol->fdl_holdcount = 0;
3590 fdtol->fdl_wakeup = 0;
3591 fdtol->fdl_leader = leader;
3593 FILEDESC_XLOCK(fdp);
3594 fdtol->fdl_next = old->fdl_next;
3595 fdtol->fdl_prev = old;
3596 old->fdl_next = fdtol;
3597 fdtol->fdl_next->fdl_prev = fdtol;
3598 FILEDESC_XUNLOCK(fdp);
3600 fdtol->fdl_next = fdtol;
3601 fdtol->fdl_prev = fdtol;
3607 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3609 struct filedesc *fdp;
3610 int i, count, slots;
3612 if (*(int *)arg1 != 0)
3615 fdp = curproc->p_fd;
3617 FILEDESC_SLOCK(fdp);
3618 slots = NDSLOTS(fdp->fd_lastfile + 1);
3619 for (i = 0; i < slots; i++)
3620 count += bitcountl(fdp->fd_map[i]);
3621 FILEDESC_SUNLOCK(fdp);
3623 return (SYSCTL_OUT(req, &count, sizeof(count)));
3626 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3627 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3628 "Number of open file descriptors");
3631 * Get file structures globally.
3634 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3637 struct filedesc *fdp;
3642 error = sysctl_wire_old_buffer(req, 0);
3645 if (req->oldptr == NULL) {
3647 sx_slock(&allproc_lock);
3648 FOREACH_PROC_IN_SYSTEM(p) {
3650 if (p->p_state == PRS_NEW) {
3658 /* overestimates sparse tables. */
3659 if (fdp->fd_lastfile > 0)
3660 n += fdp->fd_lastfile;
3663 sx_sunlock(&allproc_lock);
3664 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3667 bzero(&xf, sizeof(xf));
3668 xf.xf_size = sizeof(xf);
3669 sx_slock(&allproc_lock);
3670 FOREACH_PROC_IN_SYSTEM(p) {
3672 if (p->p_state == PRS_NEW) {
3676 if (p_cansee(req->td, p) != 0) {
3680 xf.xf_pid = p->p_pid;
3681 xf.xf_uid = p->p_ucred->cr_uid;
3686 FILEDESC_SLOCK(fdp);
3687 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3688 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3691 xf.xf_file = (uintptr_t)fp;
3692 xf.xf_data = (uintptr_t)fp->f_data;
3693 xf.xf_vnode = (uintptr_t)fp->f_vnode;
3694 xf.xf_type = (uintptr_t)fp->f_type;
3695 xf.xf_count = fp->f_count;
3697 xf.xf_offset = foffset_get(fp);
3698 xf.xf_flag = fp->f_flag;
3699 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3703 FILEDESC_SUNLOCK(fdp);
3708 sx_sunlock(&allproc_lock);
3712 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3713 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3715 #ifdef KINFO_FILE_SIZE
3716 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3720 xlate_fflags(int fflags)
3722 static const struct {
3725 } fflags_table[] = {
3726 { FAPPEND, KF_FLAG_APPEND },
3727 { FASYNC, KF_FLAG_ASYNC },
3728 { FFSYNC, KF_FLAG_FSYNC },
3729 { FHASLOCK, KF_FLAG_HASLOCK },
3730 { FNONBLOCK, KF_FLAG_NONBLOCK },
3731 { FREAD, KF_FLAG_READ },
3732 { FWRITE, KF_FLAG_WRITE },
3733 { O_CREAT, KF_FLAG_CREAT },
3734 { O_DIRECT, KF_FLAG_DIRECT },
3735 { O_EXCL, KF_FLAG_EXCL },
3736 { O_EXEC, KF_FLAG_EXEC },
3737 { O_EXLOCK, KF_FLAG_EXLOCK },
3738 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3739 { O_SHLOCK, KF_FLAG_SHLOCK },
3740 { O_TRUNC, KF_FLAG_TRUNC }
3746 for (i = 0; i < nitems(fflags_table); i++)
3747 if (fflags & fflags_table[i].fflag)
3748 kflags |= fflags_table[i].kf_fflag;
3752 /* Trim unused data from kf_path by truncating the structure size. */
3754 pack_kinfo(struct kinfo_file *kif)
3757 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3758 strlen(kif->kf_path) + 1;
3759 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3763 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3764 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3768 bzero(kif, sizeof(*kif));
3770 /* Set a default type to allow for empty fill_kinfo() methods. */
3771 kif->kf_type = KF_TYPE_UNKNOWN;
3772 kif->kf_flags = xlate_fflags(fp->f_flag);
3773 if (rightsp != NULL)
3774 kif->kf_cap_rights = *rightsp;
3776 cap_rights_init_zero(&kif->kf_cap_rights);
3778 kif->kf_ref_count = fp->f_count;
3779 kif->kf_offset = foffset_get(fp);
3782 * This may drop the filedesc lock, so the 'fp' cannot be
3783 * accessed after this call.
3785 error = fo_fill_kinfo(fp, kif, fdp);
3787 kif->kf_status |= KF_ATTR_VALID;
3788 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3791 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3795 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3796 struct kinfo_file *kif, int flags)
3800 bzero(kif, sizeof(*kif));
3802 kif->kf_type = KF_TYPE_VNODE;
3803 error = vn_fill_kinfo_vnode(vp, kif);
3805 kif->kf_status |= KF_ATTR_VALID;
3806 kif->kf_flags = xlate_fflags(fflags);
3807 cap_rights_init_zero(&kif->kf_cap_rights);
3809 kif->kf_ref_count = -1;
3810 kif->kf_offset = -1;
3811 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3814 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3818 struct export_fd_buf {
3819 struct filedesc *fdp;
3822 struct kinfo_file kif;
3827 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3829 struct kinfo_file *kif;
3832 if (efbuf->remainder != -1) {
3833 if (efbuf->remainder < kif->kf_structsize) {
3834 /* Terminate export. */
3835 efbuf->remainder = 0;
3838 efbuf->remainder -= kif->kf_structsize;
3840 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3844 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3845 struct export_fd_buf *efbuf)
3849 if (efbuf->remainder == 0)
3851 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3853 FILEDESC_SUNLOCK(efbuf->fdp);
3854 error = export_kinfo_to_sb(efbuf);
3855 FILEDESC_SLOCK(efbuf->fdp);
3860 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3861 struct export_fd_buf *efbuf)
3865 if (efbuf->remainder == 0)
3867 if (efbuf->fdp != NULL)
3868 FILEDESC_SUNLOCK(efbuf->fdp);
3869 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3870 error = export_kinfo_to_sb(efbuf);
3871 if (efbuf->fdp != NULL)
3872 FILEDESC_SLOCK(efbuf->fdp);
3877 * Store a process file descriptor information to sbuf.
3879 * Takes a locked proc as argument, and returns with the proc unlocked.
3882 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3886 struct filedesc *fdp;
3887 struct export_fd_buf *efbuf;
3888 struct vnode *cttyvp, *textvp, *tracevp;
3891 cap_rights_t rights;
3893 PROC_LOCK_ASSERT(p, MA_OWNED);
3896 tracevp = p->p_tracevp;
3897 if (tracevp != NULL)
3900 textvp = p->p_textvp;
3903 /* Controlling tty. */
3905 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3906 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3912 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3915 efbuf->remainder = maxlen;
3916 efbuf->flags = flags;
3917 if (tracevp != NULL)
3918 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3921 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3923 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3929 FILEDESC_SLOCK(fdp);
3930 pwd = pwd_hold_filedesc(fdp);
3932 /* working directory */
3933 if (pwd->pwd_cdir != NULL) {
3934 vrefact(pwd->pwd_cdir);
3935 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3937 /* root directory */
3938 if (pwd->pwd_rdir != NULL) {
3939 vrefact(pwd->pwd_rdir);
3940 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3942 /* jail directory */
3943 if (pwd->pwd_jdir != NULL) {
3944 vrefact(pwd->pwd_jdir);
3945 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3949 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3950 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3953 rights = *cap_rights(fdp, i);
3954 #else /* !CAPABILITIES */
3955 rights = cap_no_rights;
3958 * Create sysctl entry. It is OK to drop the filedesc
3959 * lock inside of export_file_to_sb() as we will
3960 * re-validate and re-evaluate its properties when the
3963 error = export_file_to_sb(fp, i, &rights, efbuf);
3964 if (error != 0 || efbuf->remainder == 0)
3967 FILEDESC_SUNLOCK(fdp);
3970 free(efbuf, M_TEMP);
3974 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3977 * Get per-process file descriptors for use by procstat(1), et al.
3980 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3985 int error, error2, *name;
3989 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3990 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3991 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3996 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3997 error = kern_proc_filedesc_out(p, &sb, maxlen,
3998 KERN_FILEDESC_PACK_KINFO);
3999 error2 = sbuf_finish(&sb);
4001 return (error != 0 ? error : error2);
4004 #ifdef COMPAT_FREEBSD7
4005 #ifdef KINFO_OFILE_SIZE
4006 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4010 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4013 okif->kf_structsize = sizeof(*okif);
4014 okif->kf_type = kif->kf_type;
4015 okif->kf_fd = kif->kf_fd;
4016 okif->kf_ref_count = kif->kf_ref_count;
4017 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4018 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4019 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4020 okif->kf_offset = kif->kf_offset;
4021 if (kif->kf_type == KF_TYPE_VNODE)
4022 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4024 okif->kf_vnode_type = KF_VTYPE_VNON;
4025 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4026 if (kif->kf_type == KF_TYPE_SOCKET) {
4027 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4028 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4029 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4030 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4031 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4033 okif->kf_sa_local.ss_family = AF_UNSPEC;
4034 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4039 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4040 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
4045 FILEDESC_SUNLOCK(fdp);
4046 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4047 kinfo_to_okinfo(kif, okif);
4048 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4049 FILEDESC_SLOCK(fdp);
4054 * Get per-process file descriptors for use by procstat(1), et al.
4057 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4059 struct kinfo_ofile *okif;
4060 struct kinfo_file *kif;
4061 struct filedesc *fdp;
4063 int error, i, *name;
4068 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4075 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4076 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4077 FILEDESC_SLOCK(fdp);
4078 pwd = pwd_hold_filedesc(fdp);
4080 if (pwd->pwd_cdir != NULL)
4081 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4083 if (pwd->pwd_rdir != NULL)
4084 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4086 if (pwd->pwd_jdir != NULL)
4087 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4091 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4092 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4094 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4095 KERN_FILEDESC_PACK_KINFO);
4096 FILEDESC_SUNLOCK(fdp);
4097 kinfo_to_okinfo(kif, okif);
4098 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4099 FILEDESC_SLOCK(fdp);
4103 FILEDESC_SUNLOCK(fdp);
4110 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4111 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4112 "Process ofiledesc entries");
4113 #endif /* COMPAT_FREEBSD7 */
4116 vntype_to_kinfo(int vtype)
4121 } vtypes_table[] = {
4122 { VBAD, KF_VTYPE_VBAD },
4123 { VBLK, KF_VTYPE_VBLK },
4124 { VCHR, KF_VTYPE_VCHR },
4125 { VDIR, KF_VTYPE_VDIR },
4126 { VFIFO, KF_VTYPE_VFIFO },
4127 { VLNK, KF_VTYPE_VLNK },
4128 { VNON, KF_VTYPE_VNON },
4129 { VREG, KF_VTYPE_VREG },
4130 { VSOCK, KF_VTYPE_VSOCK }
4135 * Perform vtype translation.
4137 for (i = 0; i < nitems(vtypes_table); i++)
4138 if (vtypes_table[i].vtype == vtype)
4139 return (vtypes_table[i].kf_vtype);
4141 return (KF_VTYPE_UNKNOWN);
4144 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4145 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4146 "Process filedesc entries");
4149 * Store a process current working directory information to sbuf.
4151 * Takes a locked proc as argument, and returns with the proc unlocked.
4154 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4156 struct filedesc *fdp;
4158 struct export_fd_buf *efbuf;
4162 PROC_LOCK_ASSERT(p, MA_OWNED);
4169 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4172 efbuf->remainder = maxlen;
4174 FILEDESC_SLOCK(fdp);
4175 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4176 cdir = pwd->pwd_cdir;
4181 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4183 FILEDESC_SUNLOCK(fdp);
4185 free(efbuf, M_TEMP);
4190 * Get per-process current working directory.
4193 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4198 int error, error2, *name;
4202 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4203 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4204 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4209 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4210 error = kern_proc_cwd_out(p, &sb, maxlen);
4211 error2 = sbuf_finish(&sb);
4213 return (error != 0 ? error : error2);
4216 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4217 sysctl_kern_proc_cwd, "Process current working directory");
4221 * For the purposes of debugging, generate a human-readable string for the
4225 file_type_to_name(short type)
4253 case DTYPE_PROCDESC:
4255 case DTYPE_LINUXEFD:
4257 case DTYPE_LINUXTFD:
4265 * For the purposes of debugging, identify a process (if any, perhaps one of
4266 * many) that references the passed file in its file descriptor array. Return
4269 static struct proc *
4270 file_to_first_proc(struct file *fp)
4272 struct filedesc *fdp;
4276 FOREACH_PROC_IN_SYSTEM(p) {
4277 if (p->p_state == PRS_NEW)
4282 for (n = 0; n <= fdp->fd_lastfile; n++) {
4283 if (fp == fdp->fd_ofiles[n].fde_file)
4291 db_print_file(struct file *fp, int header)
4293 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4297 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4298 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4299 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4301 p = file_to_first_proc(fp);
4302 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4303 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4304 fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4305 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4310 DB_SHOW_COMMAND(file, db_show_file)
4315 db_printf("usage: show file <addr>\n");
4318 fp = (struct file *)addr;
4319 db_print_file(fp, 1);
4322 DB_SHOW_COMMAND(files, db_show_files)
4324 struct filedesc *fdp;
4331 FOREACH_PROC_IN_SYSTEM(p) {
4332 if (p->p_state == PRS_NEW)
4334 if ((fdp = p->p_fd) == NULL)
4336 for (n = 0; n <= fdp->fd_lastfile; ++n) {
4337 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4339 db_print_file(fp, header);
4346 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4347 &maxfilesperproc, 0, "Maximum files allowed open per process");
4349 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4350 &maxfiles, 0, "Maximum number of files");
4352 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4353 &openfiles, 0, "System-wide number of open files");
4357 filelistinit(void *dummy)
4360 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4361 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4362 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4363 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4364 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4365 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4366 pwd_smr = uma_zone_get_smr(pwd_zone);
4367 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4369 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4371 /*-------------------------------------------------------------------*/
4374 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4375 int flags, struct thread *td)
4382 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4390 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4398 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4406 badfo_kqfilter(struct file *fp, struct knote *kn)
4413 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4421 badfo_close(struct file *fp, struct thread *td)
4428 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4436 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4444 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4445 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4453 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4459 struct fileops badfileops = {
4460 .fo_read = badfo_readwrite,
4461 .fo_write = badfo_readwrite,
4462 .fo_truncate = badfo_truncate,
4463 .fo_ioctl = badfo_ioctl,
4464 .fo_poll = badfo_poll,
4465 .fo_kqfilter = badfo_kqfilter,
4466 .fo_stat = badfo_stat,
4467 .fo_close = badfo_close,
4468 .fo_chmod = badfo_chmod,
4469 .fo_chown = badfo_chown,
4470 .fo_sendfile = badfo_sendfile,
4471 .fo_fill_kinfo = badfo_fill_kinfo,
4475 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4476 int flags, struct thread *td)
4479 return (EOPNOTSUPP);
4483 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4491 invfo_ioctl(struct file *fp, u_long com, void *data,
4492 struct ucred *active_cred, struct thread *td)
4499 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4503 return (poll_no_poll(events));
4507 invfo_kqfilter(struct file *fp, struct knote *kn)
4514 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4522 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4530 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4531 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4538 /*-------------------------------------------------------------------*/
4541 * File Descriptor pseudo-device driver (/dev/fd/).
4543 * Opening minor device N dup()s the file (if any) connected to file
4544 * descriptor N belonging to the calling process. Note that this driver
4545 * consists of only the ``open()'' routine, because all subsequent
4546 * references to this file will be direct to the other driver.
4548 * XXX: we could give this one a cloning event handler if necessary.
4553 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4557 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4558 * the file descriptor being sought for duplication. The error
4559 * return ensures that the vnode for this device will be released
4560 * by vn_open. Open will detect this special error and take the
4561 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4562 * will simply report the error.
4564 td->td_dupfd = dev2unit(dev);
4568 static struct cdevsw fildesc_cdevsw = {
4569 .d_version = D_VERSION,
4575 fildesc_drvinit(void *unused)
4579 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4580 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4581 make_dev_alias(dev, "stdin");
4582 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4583 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4584 make_dev_alias(dev, "stdout");
4585 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4586 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4587 make_dev_alias(dev, "stderr");
4590 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);