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 #include "opt_capsicum.h"
42 #include "opt_ktrace.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
47 #include <sys/capsicum.h>
49 #include <sys/fcntl.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/mutex.h>
60 #include <sys/namei.h>
61 #include <sys/selinfo.h>
65 #include <sys/protosw.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
69 #include <sys/signalvar.h>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 #include <sys/sysproto.h>
77 #include <sys/unistd.h>
79 #include <sys/vnode.h>
80 #include <sys/ktrace.h>
84 #include <security/audit/audit.h>
91 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
92 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
93 static MALLOC_DEFINE(M_PWDDESC, "pwddesc", "Pwd descriptors");
94 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
95 "file desc to leader structures");
96 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
97 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
99 MALLOC_DECLARE(M_FADVISE);
101 static __read_mostly uma_zone_t file_zone;
102 static __read_mostly uma_zone_t filedesc0_zone;
103 __read_mostly uma_zone_t pwd_zone;
106 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
107 struct thread *td, bool holdleaders, bool audit);
108 static void export_file_to_kinfo(struct file *fp, int fd,
109 cap_rights_t *rightsp, struct kinfo_file *kif,
110 struct filedesc *fdp, int flags);
111 static int fd_first_free(struct filedesc *fdp, int low, 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 fget_unlocked_seq(struct thread *td, int fd,
117 cap_rights_t *needrightsp, struct file **fpp, seqc_t *seqp);
118 static int getmaxfd(struct thread *td);
119 static u_long *filecaps_copy_prep(const struct filecaps *src);
120 static void filecaps_copy_finish(const struct filecaps *src,
121 struct filecaps *dst, u_long *ioctls);
122 static u_long *filecaps_free_prep(struct filecaps *fcaps);
123 static void filecaps_free_finish(u_long *ioctls);
125 static struct pwd *pwd_alloc(void);
130 * - An array of open file descriptors (fd_ofiles)
131 * - An array of file flags (fd_ofileflags)
132 * - A bitmap recording which descriptors are in use (fd_map)
134 * A process starts out with NDFILE descriptors. The value of NDFILE has
135 * been selected based the historical limit of 20 open files, and an
136 * assumption that the majority of processes, especially short-lived
137 * processes like shells, will never need more.
139 * If this initial allocation is exhausted, a larger descriptor table and
140 * map are allocated dynamically, and the pointers in the process's struct
141 * filedesc are updated to point to those. This is repeated every time
142 * the process runs out of file descriptors (provided it hasn't hit its
145 * Since threads may hold references to individual descriptor table
146 * entries, the tables are never freed. Instead, they are placed on a
147 * linked list and freed only when the struct filedesc is released.
150 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
151 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
152 #define NDSLOT(x) ((x) / NDENTRIES)
153 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
154 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
156 #define FILEDESC_FOREACH_FDE(fdp, _iterator, _fde) \
157 struct filedesc *_fdp = (fdp); \
158 int _lastfile = fdlastfile_single(_fdp); \
159 for (_iterator = 0; _iterator <= _lastfile; _iterator++) \
160 if ((_fde = &_fdp->fd_ofiles[_iterator])->fde_file != NULL)
162 #define FILEDESC_FOREACH_FP(fdp, _iterator, _fp) \
163 struct filedesc *_fdp = (fdp); \
164 int _lastfile = fdlastfile_single(_fdp); \
165 for (_iterator = 0; _iterator <= _lastfile; _iterator++) \
166 if ((_fp = _fdp->fd_ofiles[_iterator].fde_file) != NULL)
169 * SLIST entry used to keep track of ofiles which must be reclaimed when
173 struct fdescenttbl *ft_table;
174 SLIST_ENTRY(freetable) ft_next;
178 * Initial allocation: a filedesc structure + the head of SLIST used to
179 * keep track of old ofiles + enough space for NDFILE descriptors.
182 struct fdescenttbl0 {
184 struct filedescent fdt_ofiles[NDFILE];
188 struct filedesc fd_fd;
189 SLIST_HEAD(, freetable) fd_free;
190 struct fdescenttbl0 fd_dfiles;
191 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
195 * Descriptor management.
197 static int __exclusive_cache_line openfiles; /* actual number of open files */
198 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
199 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
202 * If low >= size, just return low. Otherwise find the first zero bit in the
203 * given bitmap, starting at low and not exceeding size - 1. Return size if
207 fd_first_free(struct filedesc *fdp, int low, int size)
209 NDSLOTTYPE *map = fdp->fd_map;
217 if (low % NDENTRIES) {
218 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
219 if ((mask &= ~map[off]) != 0UL)
220 return (off * NDENTRIES + ffsl(mask) - 1);
223 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
224 if (map[off] != ~0UL)
225 return (off * NDENTRIES + ffsl(~map[off]) - 1);
230 * Find the last used fd.
232 * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
233 * Otherwise use fdlastfile.
236 fdlastfile_single(struct filedesc *fdp)
238 NDSLOTTYPE *map = fdp->fd_map;
241 off = NDSLOT(fdp->fd_nfiles - 1);
242 for (minoff = NDSLOT(0); off >= minoff; --off)
244 return (off * NDENTRIES + flsl(map[off]) - 1);
249 fdlastfile(struct filedesc *fdp)
252 FILEDESC_LOCK_ASSERT(fdp);
253 return (fdlastfile_single(fdp));
257 fdisused(struct filedesc *fdp, int fd)
260 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
261 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
263 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
267 * Mark a file descriptor as used.
270 fdused_init(struct filedesc *fdp, int fd)
273 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
275 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
279 fdused(struct filedesc *fdp, int fd)
282 FILEDESC_XLOCK_ASSERT(fdp);
284 fdused_init(fdp, fd);
285 if (fd == fdp->fd_freefile)
290 * Mark a file descriptor as unused.
293 fdunused(struct filedesc *fdp, int fd)
296 FILEDESC_XLOCK_ASSERT(fdp);
298 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
299 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
300 ("fd=%d is still in use", fd));
302 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
303 if (fd < fdp->fd_freefile)
304 fdp->fd_freefile = fd;
308 * Free a file descriptor.
310 * Avoid some work if fdp is about to be destroyed.
313 fdefree_last(struct filedescent *fde)
316 filecaps_free(&fde->fde_caps);
320 fdfree(struct filedesc *fdp, int fd)
322 struct filedescent *fde;
324 FILEDESC_XLOCK_ASSERT(fdp);
325 fde = &fdp->fd_ofiles[fd];
327 seqc_write_begin(&fde->fde_seqc);
329 fde->fde_file = NULL;
331 seqc_write_end(&fde->fde_seqc);
338 * System calls on descriptors.
340 #ifndef _SYS_SYSPROTO_H_
341 struct getdtablesize_args {
347 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
353 td->td_retval[0] = getmaxfd(td);
355 PROC_LOCK(td->td_proc);
356 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
357 PROC_UNLOCK(td->td_proc);
358 if (lim < td->td_retval[0])
359 td->td_retval[0] = lim;
365 * Duplicate a file descriptor to a particular value.
367 * Note: keep in mind that a potential race condition exists when closing
368 * descriptors from a shared descriptor table (via rfork).
370 #ifndef _SYS_SYSPROTO_H_
378 sys_dup2(struct thread *td, struct dup2_args *uap)
381 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
385 * Duplicate a file descriptor.
387 #ifndef _SYS_SYSPROTO_H_
394 sys_dup(struct thread *td, struct dup_args *uap)
397 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
401 * The file control system call.
403 #ifndef _SYS_SYSPROTO_H_
412 sys_fcntl(struct thread *td, struct fcntl_args *uap)
415 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
419 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
433 * Convert old flock structure to new.
435 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
436 fl.l_start = ofl.l_start;
437 fl.l_len = ofl.l_len;
438 fl.l_pid = ofl.l_pid;
439 fl.l_type = ofl.l_type;
440 fl.l_whence = ofl.l_whence;
454 arg1 = (intptr_t)&fl;
460 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
461 arg1 = (intptr_t)&fl;
469 error = kern_fcntl(td, fd, newcmd, arg1);
472 if (cmd == F_OGETLK) {
473 ofl.l_start = fl.l_start;
474 ofl.l_len = fl.l_len;
475 ofl.l_pid = fl.l_pid;
476 ofl.l_type = fl.l_type;
477 ofl.l_whence = fl.l_whence;
478 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
479 } else if (cmd == F_GETLK) {
480 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
486 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
488 struct filedesc *fdp;
490 struct file *fp, *fp2;
491 struct filedescent *fde;
495 struct kinfo_file *kif;
496 int error, flg, kif_sz, seals, tmp, got_set, got_cleared;
510 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
513 case F_DUPFD_CLOEXEC:
515 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
520 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
523 case F_DUP2FD_CLOEXEC:
525 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
531 fde = fdeget_noref(fdp, fd);
534 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
537 FILEDESC_SUNLOCK(fdp);
543 fde = fdeget_noref(fdp, fd);
545 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
546 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
549 FILEDESC_XUNLOCK(fdp);
553 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
556 td->td_retval[0] = OFLAGS(fp->f_flag);
561 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
564 if (fp->f_ops == &path_fileops) {
570 tmp = flg = fp->f_flag;
572 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
573 } while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
574 got_set = tmp & ~flg;
575 got_cleared = flg & ~tmp;
576 tmp = fp->f_flag & FNONBLOCK;
577 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
580 tmp = fp->f_flag & FASYNC;
581 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
586 atomic_clear_int(&fp->f_flag, FNONBLOCK);
588 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
591 tmp = flg = fp->f_flag;
595 } while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
600 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
603 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
605 td->td_retval[0] = tmp;
610 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
614 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
619 error = priv_check(td, PRIV_NFS_LOCKD);
627 /* FALLTHROUGH F_SETLK */
631 flp = (struct flock *)arg;
632 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
637 error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
640 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
646 if (flp->l_whence == SEEK_CUR) {
647 foffset = foffset_get(fp);
650 foffset > OFF_MAX - flp->l_start)) {
655 flp->l_start += foffset;
659 switch (flp->l_type) {
661 if ((fp->f_flag & FREAD) == 0) {
665 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
666 PROC_LOCK(p->p_leader);
667 p->p_leader->p_flag |= P_ADVLOCK;
668 PROC_UNLOCK(p->p_leader);
670 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
674 if ((fp->f_flag & FWRITE) == 0) {
678 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
679 PROC_LOCK(p->p_leader);
680 p->p_leader->p_flag |= P_ADVLOCK;
681 PROC_UNLOCK(p->p_leader);
683 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
687 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
691 if (flg != F_REMOTE) {
695 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
696 F_UNLCKSYS, flp, flg);
702 if (error != 0 || flp->l_type == F_UNLCK ||
703 flp->l_type == F_UNLCKSYS) {
709 * Check for a race with close.
711 * The vnode is now advisory locked (or unlocked, but this case
712 * is not really important) as the caller requested.
713 * We had to drop the filedesc lock, so we need to recheck if
714 * the descriptor is still valid, because if it was closed
715 * in the meantime we need to remove advisory lock from the
716 * vnode - close on any descriptor leading to an advisory
717 * locked vnode, removes that lock.
718 * We will return 0 on purpose in that case, as the result of
719 * successful advisory lock might have been externally visible
720 * already. This is fine - effectively we pretend to the caller
721 * that the closing thread was a bit slower and that the
722 * advisory lock succeeded before the close.
724 error = fget_unlocked(td, fd, &cap_no_rights, &fp2);
730 flp->l_whence = SEEK_SET;
733 flp->l_type = F_UNLCK;
734 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
735 F_UNLCK, flp, F_POSIX);
742 error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
745 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
750 flp = (struct flock *)arg;
751 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
752 flp->l_type != F_UNLCK) {
757 if (flp->l_whence == SEEK_CUR) {
758 foffset = foffset_get(fp);
759 if ((flp->l_start > 0 &&
760 foffset > OFF_MAX - flp->l_start) ||
762 foffset < OFF_MIN - flp->l_start)) {
767 flp->l_start += foffset;
770 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
776 error = fget_unlocked(td, fd, &cap_no_rights, &fp);
779 error = fo_add_seals(fp, arg);
784 error = fget_unlocked(td, fd, &cap_no_rights, &fp);
787 if (fo_get_seals(fp, &seals) == 0)
788 td->td_retval[0] = seals;
795 arg = arg ? 128 * 1024: 0;
798 error = fget_unlocked(td, fd, &cap_no_rights, &fp);
801 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
807 if (vp->v_type != VREG) {
814 * Exclusive lock synchronizes against f_seqcount reads and
815 * writes in sequential_heuristic().
817 error = vn_lock(vp, LK_EXCLUSIVE);
823 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
824 arg = MIN(arg, INT_MAX - bsize + 1);
825 fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
826 (arg + bsize - 1) / bsize);
827 atomic_set_int(&fp->f_flag, FRDAHEAD);
829 atomic_clear_int(&fp->f_flag, FRDAHEAD);
837 * Check if the vnode is part of a union stack (either the
838 * "union" flag from mount(2) or unionfs).
840 * Prior to introduction of this op libc's readdir would call
841 * fstatfs(2), in effect unnecessarily copying kilobytes of
842 * data just to check fs name and a mount flag.
844 * Fixing the code to handle everything in the kernel instead
845 * is a non-trivial endeavor and has low priority, thus this
846 * horrible kludge facilitates the current behavior in a much
847 * cheaper manner until someone(tm) sorts this out.
849 error = fget_unlocked(td, fd, &cap_no_rights, &fp);
852 if (fp->f_type != DTYPE_VNODE) {
859 * Since we don't prevent dooming the vnode even non-null mp
860 * found can become immediately stale. This is tolerable since
861 * mount points are type-stable (providing safe memory access)
862 * and any vfs op on this vnode going forward will return an
863 * error (meaning return value in this case is meaningless).
865 mp = atomic_load_ptr(&vp->v_mount);
866 if (__predict_false(mp == NULL)) {
871 td->td_retval[0] = 0;
872 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
873 mp->mnt_flag & MNT_UNION)
874 td->td_retval[0] = 1;
879 #ifdef CAPABILITY_MODE
880 if (IN_CAPABILITY_MODE(td)) {
885 error = copyin((void *)arg, &kif_sz, sizeof(kif_sz));
888 if (kif_sz != sizeof(*kif)) {
892 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK | M_ZERO);
894 error = fget_cap_noref(fdp, fd, &cap_fcntl_rights, &fp, NULL);
895 if (error == 0 && fhold(fp)) {
896 export_file_to_kinfo(fp, fd, NULL, kif, fdp, 0);
897 FILEDESC_SUNLOCK(fdp);
899 if ((kif->kf_status & KF_ATTR_VALID) != 0) {
900 kif->kf_structsize = sizeof(*kif);
901 error = copyout(kif, (void *)arg, sizeof(*kif));
906 FILEDESC_SUNLOCK(fdp);
921 getmaxfd(struct thread *td)
924 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
928 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
931 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
933 struct filedesc *fdp;
934 struct filedescent *oldfde, *newfde;
936 struct file *delfp, *oldfp;
937 u_long *oioctls, *nioctls;
944 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
945 MPASS(mode < FDDUP_LASTMODE);
948 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
951 * Verify we have a valid descriptor to dup from and possibly to
952 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
953 * return EINVAL when the new descriptor is out of bounds.
958 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
959 maxfd = getmaxfd(td);
961 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
965 if (fget_noref(fdp, old) == NULL)
967 if (mode == FDDUP_FIXED && old == new) {
968 td->td_retval[0] = new;
969 if (flags & FDDUP_FLAG_CLOEXEC)
970 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
975 oldfde = &fdp->fd_ofiles[old];
976 oldfp = oldfde->fde_file;
981 * If the caller specified a file descriptor, make sure the file
982 * table is large enough to hold it, and grab it. Otherwise, just
983 * allocate a new descriptor the usual way.
988 if ((error = fdalloc(td, new, &new)) != 0) {
994 if (new >= fdp->fd_nfiles) {
996 * The resource limits are here instead of e.g.
997 * fdalloc(), because the file descriptor table may be
998 * shared between processes, so we can't really use
999 * racct_add()/racct_sub(). Instead of counting the
1000 * number of actually allocated descriptors, just put
1001 * the limit on the size of the file descriptor table.
1004 if (RACCT_ENABLED()) {
1005 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
1013 fdgrowtable_exp(fdp, new + 1);
1015 if (!fdisused(fdp, new))
1019 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
1022 KASSERT(old != new, ("new fd is same as old"));
1024 /* Refetch oldfde because the table may have grown and old one freed. */
1025 oldfde = &fdp->fd_ofiles[old];
1026 KASSERT(oldfp == oldfde->fde_file,
1027 ("fdt_ofiles shift from growth observed at fd %d",
1030 newfde = &fdp->fd_ofiles[new];
1031 delfp = newfde->fde_file;
1033 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
1036 * Duplicate the source descriptor.
1039 seqc_write_begin(&newfde->fde_seqc);
1041 oioctls = filecaps_free_prep(&newfde->fde_caps);
1042 fde_copy(oldfde, newfde);
1043 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
1045 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
1046 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
1048 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
1050 seqc_write_end(&newfde->fde_seqc);
1052 td->td_retval[0] = new;
1056 if (delfp != NULL) {
1057 (void) closefp(fdp, new, delfp, td, true, false);
1058 FILEDESC_UNLOCK_ASSERT(fdp);
1061 FILEDESC_XUNLOCK(fdp);
1064 filecaps_free_finish(oioctls);
1069 sigiofree(struct sigio *sigio)
1071 crfree(sigio->sio_ucred);
1072 free(sigio, M_SIGIO);
1075 static struct sigio *
1076 funsetown_locked(struct sigio *sigio)
1081 SIGIO_ASSERT_LOCKED();
1085 *sigio->sio_myref = NULL;
1086 if (sigio->sio_pgid < 0) {
1087 pg = sigio->sio_pgrp;
1089 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1092 p = sigio->sio_proc;
1094 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1101 * If sigio is on the list associated with a process or process group,
1102 * disable signalling from the device, remove sigio from the list and
1106 funsetown(struct sigio **sigiop)
1108 struct sigio *sigio;
1110 /* Racy check, consumers must provide synchronization. */
1111 if (*sigiop == NULL)
1115 sigio = funsetown_locked(*sigiop);
1122 * Free a list of sigio structures. The caller must ensure that new sigio
1123 * structures cannot be added after this point. For process groups this is
1124 * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1128 funsetownlst(struct sigiolst *sigiolst)
1132 struct sigio *sigio, *tmp;
1135 sigio = SLIST_FIRST(sigiolst);
1143 sigio = SLIST_FIRST(sigiolst);
1144 if (sigio == NULL) {
1150 * Every entry of the list should belong to a single proc or pgrp.
1152 if (sigio->sio_pgid < 0) {
1153 pg = sigio->sio_pgrp;
1154 sx_assert(&proctree_lock, SX_XLOCKED);
1156 } else /* if (sigio->sio_pgid > 0) */ {
1157 p = sigio->sio_proc;
1159 KASSERT((p->p_flag & P_WEXIT) != 0,
1160 ("%s: process %p is not exiting", __func__, p));
1163 SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1164 *sigio->sio_myref = NULL;
1166 KASSERT(sigio->sio_pgid < 0,
1167 ("Proc sigio in pgrp sigio list"));
1168 KASSERT(sigio->sio_pgrp == pg,
1169 ("Bogus pgrp in sigio list"));
1170 } else /* if (p != NULL) */ {
1171 KASSERT(sigio->sio_pgid > 0,
1172 ("Pgrp sigio in proc sigio list"));
1173 KASSERT(sigio->sio_proc == p,
1174 ("Bogus proc in sigio list"));
1184 SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1189 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1191 * After permission checking, add a sigio structure to the sigio list for
1192 * the process or process group.
1195 fsetown(pid_t pgid, struct sigio **sigiop)
1199 struct sigio *osigio, *sigio;
1207 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1208 sigio->sio_pgid = pgid;
1209 sigio->sio_ucred = crhold(curthread->td_ucred);
1210 sigio->sio_myref = sigiop;
1214 ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1216 osigio = funsetown_locked(*sigiop);
1220 if ((proc->p_flag & P_WEXIT) != 0) {
1222 } else if (proc->p_session !=
1223 curthread->td_proc->p_session) {
1225 * Policy - Don't allow a process to FSETOWN a
1226 * process in another session.
1228 * Remove this test to allow maximum flexibility
1229 * or restrict FSETOWN to the current process or
1230 * process group for maximum safety.
1234 sigio->sio_proc = proc;
1235 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1240 } else /* if (pgid < 0) */ {
1241 sx_slock(&proctree_lock);
1243 osigio = funsetown_locked(*sigiop);
1244 pgrp = pgfind(-pgid);
1248 if (pgrp->pg_session != curthread->td_proc->p_session) {
1250 * Policy - Don't allow a process to FSETOWN a
1251 * process in another session.
1253 * Remove this test to allow maximum flexibility
1254 * or restrict FSETOWN to the current process or
1255 * process group for maximum safety.
1259 sigio->sio_pgrp = pgrp;
1260 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1265 sx_sunlock(&proctree_lock);
1276 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1279 fgetown(struct sigio **sigiop)
1284 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1290 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1295 FILEDESC_XLOCK_ASSERT(fdp);
1298 * We now hold the fp reference that used to be owned by the
1299 * descriptor array. We have to unlock the FILEDESC *AFTER*
1300 * knote_fdclose to prevent a race of the fd getting opened, a knote
1301 * added, and deleteing a knote for the new fd.
1303 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1304 knote_fdclose(td, fd);
1307 * We need to notify mqueue if the object is of type mqueue.
1309 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1310 mq_fdclose(td, fd, fp);
1311 FILEDESC_XUNLOCK(fdp);
1314 if (AUDITING_TD(td) && audit)
1315 audit_sysclose(td, fd, fp);
1317 error = closef(fp, td);
1320 * All paths leading up to closefp() will have already removed or
1321 * replaced the fd in the filedesc table, so a restart would not
1322 * operate on the same file.
1324 if (error == ERESTART)
1331 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1332 bool holdleaders, bool audit)
1336 FILEDESC_XLOCK_ASSERT(fdp);
1339 if (td->td_proc->p_fdtol != NULL) {
1341 * Ask fdfree() to sleep to ensure that all relevant
1342 * process leaders can be traversed in closef().
1344 fdp->fd_holdleaderscount++;
1346 holdleaders = false;
1350 error = closefp_impl(fdp, fd, fp, td, audit);
1352 FILEDESC_XLOCK(fdp);
1353 fdp->fd_holdleaderscount--;
1354 if (fdp->fd_holdleaderscount == 0 &&
1355 fdp->fd_holdleaderswakeup != 0) {
1356 fdp->fd_holdleaderswakeup = 0;
1357 wakeup(&fdp->fd_holdleaderscount);
1359 FILEDESC_XUNLOCK(fdp);
1365 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1366 bool holdleaders, bool audit)
1369 FILEDESC_XLOCK_ASSERT(fdp);
1371 if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1372 return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1374 return (closefp_impl(fdp, fd, fp, td, audit));
1379 * Close a file descriptor.
1381 #ifndef _SYS_SYSPROTO_H_
1388 sys_close(struct thread *td, struct close_args *uap)
1391 return (kern_close(td, uap->fd));
1395 kern_close(struct thread *td, int fd)
1397 struct filedesc *fdp;
1400 fdp = td->td_proc->p_fd;
1402 FILEDESC_XLOCK(fdp);
1403 if ((fp = fget_noref(fdp, fd)) == NULL) {
1404 FILEDESC_XUNLOCK(fdp);
1409 /* closefp() drops the FILEDESC lock for us. */
1410 return (closefp(fdp, fd, fp, td, true, true));
1414 close_range_cloexec(struct thread *td, u_int lowfd, u_int highfd)
1416 struct filedesc *fdp;
1417 struct fdescenttbl *fdt;
1418 struct filedescent *fde;
1421 fdp = td->td_proc->p_fd;
1422 FILEDESC_XLOCK(fdp);
1423 fdt = atomic_load_ptr(&fdp->fd_files);
1424 highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1426 if (__predict_false(fd > highfd)) {
1429 for (; fd <= highfd; fd++) {
1430 fde = &fdt->fdt_ofiles[fd];
1431 if (fde->fde_file != NULL)
1432 fde->fde_flags |= UF_EXCLOSE;
1435 FILEDESC_XUNLOCK(fdp);
1440 close_range_impl(struct thread *td, u_int lowfd, u_int highfd)
1442 struct filedesc *fdp;
1443 const struct fdescenttbl *fdt;
1447 fdp = td->td_proc->p_fd;
1448 FILEDESC_XLOCK(fdp);
1449 fdt = atomic_load_ptr(&fdp->fd_files);
1450 highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1452 if (__predict_false(fd > highfd)) {
1456 fp = fdt->fdt_ofiles[fd].fde_file;
1462 (void) closefp(fdp, fd, fp, td, true, true);
1465 FILEDESC_XLOCK(fdp);
1466 fdt = atomic_load_ptr(&fdp->fd_files);
1471 FILEDESC_XUNLOCK(fdp);
1477 kern_close_range(struct thread *td, int flags, u_int lowfd, u_int highfd)
1481 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1482 * open should not be a usage error. From a close_range() perspective,
1483 * close_range(3, ~0U, 0) in the same scenario should also likely not
1484 * be a usage error as all fd above 3 are in-fact already closed.
1486 if (highfd < lowfd) {
1490 if ((flags & CLOSE_RANGE_CLOEXEC) != 0)
1491 return (close_range_cloexec(td, lowfd, highfd));
1493 return (close_range_impl(td, lowfd, highfd));
1496 #ifndef _SYS_SYSPROTO_H_
1497 struct close_range_args {
1504 sys_close_range(struct thread *td, struct close_range_args *uap)
1507 AUDIT_ARG_FD(uap->lowfd);
1508 AUDIT_ARG_CMD(uap->highfd);
1509 AUDIT_ARG_FFLAGS(uap->flags);
1511 if ((uap->flags & ~(CLOSE_RANGE_CLOEXEC)) != 0)
1513 return (kern_close_range(td, uap->flags, uap->lowfd, uap->highfd));
1516 #ifdef COMPAT_FREEBSD12
1518 * Close open file descriptors.
1520 #ifndef _SYS_SYSPROTO_H_
1521 struct freebsd12_closefrom_args {
1527 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1531 AUDIT_ARG_FD(uap->lowfd);
1534 * Treat negative starting file descriptor values identical to
1535 * closefrom(0) which closes all files.
1537 lowfd = MAX(0, uap->lowfd);
1538 return (kern_close_range(td, 0, lowfd, ~0U));
1540 #endif /* COMPAT_FREEBSD12 */
1542 #if defined(COMPAT_43)
1544 * Return status information about a file descriptor.
1546 #ifndef _SYS_SYSPROTO_H_
1547 struct ofstat_args {
1554 ofstat(struct thread *td, struct ofstat_args *uap)
1560 error = kern_fstat(td, uap->fd, &ub);
1563 error = copyout(&oub, uap->sb, sizeof(oub));
1567 #endif /* COMPAT_43 */
1569 #if defined(COMPAT_FREEBSD11)
1571 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1574 struct freebsd11_stat osb;
1577 error = kern_fstat(td, uap->fd, &sb);
1580 error = freebsd11_cvtstat(&sb, &osb);
1582 error = copyout(&osb, uap->sb, sizeof(osb));
1585 #endif /* COMPAT_FREEBSD11 */
1588 * Return status information about a file descriptor.
1590 #ifndef _SYS_SYSPROTO_H_
1598 sys_fstat(struct thread *td, struct fstat_args *uap)
1603 error = kern_fstat(td, uap->fd, &ub);
1605 error = copyout(&ub, uap->sb, sizeof(ub));
1610 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1617 error = fget(td, fd, &cap_fstat_rights, &fp);
1618 if (__predict_false(error != 0))
1621 AUDIT_ARG_FILE(td->td_proc, fp);
1623 error = fo_stat(fp, sbp, td->td_ucred);
1625 #ifdef __STAT_TIME_T_EXT
1626 sbp->st_atim_ext = 0;
1627 sbp->st_mtim_ext = 0;
1628 sbp->st_ctim_ext = 0;
1629 sbp->st_btim_ext = 0;
1632 if (KTRPOINT(td, KTR_STRUCT))
1633 ktrstat_error(sbp, error);
1638 #if defined(COMPAT_FREEBSD11)
1640 * Return status information about a file descriptor.
1642 #ifndef _SYS_SYSPROTO_H_
1643 struct freebsd11_nfstat_args {
1650 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1656 error = kern_fstat(td, uap->fd, &ub);
1659 error = freebsd11_cvtnstat(&ub, &nub);
1661 error = copyout(&nub, uap->sb, sizeof(nub));
1664 #endif /* COMPAT_FREEBSD11 */
1667 * Return pathconf information about a file descriptor.
1669 #ifndef _SYS_SYSPROTO_H_
1670 struct fpathconf_args {
1677 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1682 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1684 td->td_retval[0] = value;
1689 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1695 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1699 if (name == _PC_ASYNC_IO) {
1700 *valuep = _POSIX_ASYNCHRONOUS_IO;
1705 vn_lock(vp, LK_SHARED | LK_RETRY);
1706 error = VOP_PATHCONF(vp, name, valuep);
1708 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1709 if (name != _PC_PIPE_BUF) {
1724 * Copy filecaps structure allocating memory for ioctls array if needed.
1726 * The last parameter indicates whether the fdtable is locked. If it is not and
1727 * ioctls are encountered, copying fails and the caller must lock the table.
1729 * Note that if the table was not locked, the caller has to check the relevant
1730 * sequence counter to determine whether the operation was successful.
1733 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1737 if (src->fc_ioctls != NULL && !locked)
1739 memcpy(dst, src, sizeof(*src));
1740 if (src->fc_ioctls == NULL)
1743 KASSERT(src->fc_nioctls > 0,
1744 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1746 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1747 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1748 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1753 filecaps_copy_prep(const struct filecaps *src)
1758 if (__predict_true(src->fc_ioctls == NULL))
1761 KASSERT(src->fc_nioctls > 0,
1762 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1764 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1765 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1770 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1776 if (__predict_true(src->fc_ioctls == NULL)) {
1777 MPASS(ioctls == NULL);
1781 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1782 dst->fc_ioctls = ioctls;
1783 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1787 * Move filecaps structure to the new place and clear the old place.
1790 filecaps_move(struct filecaps *src, struct filecaps *dst)
1794 bzero(src, sizeof(*src));
1798 * Fill the given filecaps structure with full rights.
1801 filecaps_fill(struct filecaps *fcaps)
1804 CAP_ALL(&fcaps->fc_rights);
1805 fcaps->fc_ioctls = NULL;
1806 fcaps->fc_nioctls = -1;
1807 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1811 * Free memory allocated within filecaps structure.
1814 filecaps_free_ioctl(struct filecaps *fcaps)
1817 free(fcaps->fc_ioctls, M_FILECAPS);
1818 fcaps->fc_ioctls = NULL;
1822 filecaps_free(struct filecaps *fcaps)
1825 filecaps_free_ioctl(fcaps);
1826 bzero(fcaps, sizeof(*fcaps));
1830 filecaps_free_prep(struct filecaps *fcaps)
1834 ioctls = fcaps->fc_ioctls;
1835 bzero(fcaps, sizeof(*fcaps));
1840 filecaps_free_finish(u_long *ioctls)
1843 free(ioctls, M_FILECAPS);
1847 * Validate the given filecaps structure.
1850 filecaps_validate(const struct filecaps *fcaps, const char *func)
1853 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1854 ("%s: invalid rights", func));
1855 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1856 ("%s: invalid fcntls", func));
1857 KASSERT(fcaps->fc_fcntls == 0 ||
1858 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1859 ("%s: fcntls without CAP_FCNTL", func));
1861 * open calls without WANTIOCTLCAPS free caps but leave the counter
1864 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1865 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1866 ("%s: invalid ioctls", func));
1868 KASSERT(fcaps->fc_nioctls == 0 ||
1869 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1870 ("%s: ioctls without CAP_IOCTL", func));
1874 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1878 FILEDESC_XLOCK_ASSERT(fdp);
1880 nfd1 = fdp->fd_nfiles * 2;
1883 fdgrowtable(fdp, nfd1);
1887 * Grow the file table to accommodate (at least) nfd descriptors.
1890 fdgrowtable(struct filedesc *fdp, int nfd)
1892 struct filedesc0 *fdp0;
1893 struct freetable *ft;
1894 struct fdescenttbl *ntable;
1895 struct fdescenttbl *otable;
1896 int nnfiles, onfiles;
1897 NDSLOTTYPE *nmap, *omap;
1899 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1901 /* save old values */
1902 onfiles = fdp->fd_nfiles;
1903 otable = fdp->fd_files;
1906 /* compute the size of the new table */
1907 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1908 if (nnfiles <= onfiles)
1909 /* the table is already large enough */
1913 * Allocate a new table. We need enough space for the number of
1914 * entries, file entries themselves and the struct freetable we will use
1915 * when we decommission the table and place it on the freelist.
1916 * We place the struct freetable in the middle so we don't have
1917 * to worry about padding.
1919 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1920 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1921 sizeof(struct freetable),
1922 M_FILEDESC, M_ZERO | M_WAITOK);
1923 /* copy the old data */
1924 ntable->fdt_nfiles = nnfiles;
1925 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1926 onfiles * sizeof(ntable->fdt_ofiles[0]));
1929 * Allocate a new map only if the old is not large enough. It will
1930 * grow at a slower rate than the table as it can map more
1931 * entries than the table can hold.
1933 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1934 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1936 /* copy over the old data and update the pointer */
1937 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1942 * Make sure that ntable is correctly initialized before we replace
1943 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1946 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1949 * Free the old file table when not shared by other threads or processes.
1950 * The old file table is considered to be shared when either are true:
1951 * - The process has more than one thread.
1952 * - The file descriptor table has been shared via fdshare().
1954 * When shared, the old file table will be placed on a freelist
1955 * which will be processed when the struct filedesc is released.
1957 * Note that if onfiles == NDFILE, we're dealing with the original
1958 * static allocation contained within (struct filedesc0 *)fdp,
1959 * which must not be freed.
1961 if (onfiles > NDFILE) {
1963 * Note we may be called here from fdinit while allocating a
1964 * table for a new process in which case ->p_fd points
1967 if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1968 free(otable, M_FILEDESC);
1970 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1971 fdp0 = (struct filedesc0 *)fdp;
1972 ft->ft_table = otable;
1973 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1977 * The map does not have the same possibility of threads still
1978 * holding references to it. So always free it as long as it
1979 * does not reference the original static allocation.
1981 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1982 free(omap, M_FILEDESC);
1986 * Allocate a file descriptor for the process.
1989 fdalloc(struct thread *td, int minfd, int *result)
1991 struct proc *p = td->td_proc;
1992 struct filedesc *fdp = p->p_fd;
1993 int fd, maxfd, allocfd;
1998 FILEDESC_XLOCK_ASSERT(fdp);
2000 if (fdp->fd_freefile > minfd)
2001 minfd = fdp->fd_freefile;
2003 maxfd = getmaxfd(td);
2006 * Search the bitmap for a free descriptor starting at minfd.
2007 * If none is found, grow the file table.
2009 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
2010 if (__predict_false(fd >= maxfd))
2012 if (__predict_false(fd >= fdp->fd_nfiles)) {
2013 allocfd = min(fd * 2, maxfd);
2015 if (RACCT_ENABLED()) {
2016 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
2022 * fd is already equal to first free descriptor >= minfd, so
2023 * we only need to grow the table and we are done.
2025 fdgrowtable_exp(fdp, allocfd);
2029 * Perform some sanity checks, then mark the file descriptor as
2030 * used and return it to the caller.
2032 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
2033 ("invalid descriptor %d", fd));
2034 KASSERT(!fdisused(fdp, fd),
2035 ("fd_first_free() returned non-free descriptor"));
2036 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
2037 ("file descriptor isn't free"));
2044 * Allocate n file descriptors for the process.
2047 fdallocn(struct thread *td, int minfd, int *fds, int n)
2049 struct proc *p = td->td_proc;
2050 struct filedesc *fdp = p->p_fd;
2053 FILEDESC_XLOCK_ASSERT(fdp);
2055 for (i = 0; i < n; i++)
2056 if (fdalloc(td, 0, &fds[i]) != 0)
2060 for (i--; i >= 0; i--)
2061 fdunused(fdp, fds[i]);
2069 * Create a new open file structure and allocate a file descriptor for the
2070 * process that refers to it. We add one reference to the file for the
2071 * descriptor table and one reference for resultfp. This is to prevent us
2072 * being preempted and the entry in the descriptor table closed after we
2073 * release the FILEDESC lock.
2076 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
2077 struct filecaps *fcaps)
2082 MPASS(resultfp != NULL);
2083 MPASS(resultfd != NULL);
2085 error = _falloc_noinstall(td, &fp, 2);
2086 if (__predict_false(error != 0)) {
2090 error = finstall_refed(td, fp, &fd, flags, fcaps);
2091 if (__predict_false(error != 0)) {
2092 falloc_abort(td, fp);
2103 * Create a new open file structure without allocating a file descriptor.
2106 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2109 int maxuserfiles = maxfiles - (maxfiles / 20);
2111 static struct timeval lastfail;
2114 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2117 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2118 if ((openfiles_new >= maxuserfiles &&
2119 priv_check(td, PRIV_MAXFILES) != 0) ||
2120 openfiles_new >= maxfiles) {
2121 atomic_subtract_int(&openfiles, 1);
2122 if (ppsratecheck(&lastfail, &curfail, 1)) {
2123 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2124 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2128 fp = uma_zalloc(file_zone, M_WAITOK);
2129 bzero(fp, sizeof(*fp));
2130 refcount_init(&fp->f_count, n);
2131 fp->f_cred = crhold(td->td_ucred);
2132 fp->f_ops = &badfileops;
2138 falloc_abort(struct thread *td, struct file *fp)
2142 * For assertion purposes.
2144 refcount_init(&fp->f_count, 0);
2149 * Install a file in a file descriptor table.
2152 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2153 struct filecaps *fcaps)
2155 struct filedescent *fde;
2159 filecaps_validate(fcaps, __func__);
2160 FILEDESC_XLOCK_ASSERT(fdp);
2162 fde = &fdp->fd_ofiles[fd];
2164 seqc_write_begin(&fde->fde_seqc);
2167 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2169 filecaps_move(fcaps, &fde->fde_caps);
2171 filecaps_fill(&fde->fde_caps);
2173 seqc_write_end(&fde->fde_seqc);
2178 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2179 struct filecaps *fcaps)
2181 struct filedesc *fdp = td->td_proc->p_fd;
2186 FILEDESC_XLOCK(fdp);
2187 error = fdalloc(td, 0, fd);
2188 if (__predict_true(error == 0)) {
2189 _finstall(fdp, fp, *fd, flags, fcaps);
2191 FILEDESC_XUNLOCK(fdp);
2196 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2197 struct filecaps *fcaps)
2205 error = finstall_refed(td, fp, fd, flags, fcaps);
2206 if (__predict_false(error != 0)) {
2213 * Build a new filedesc structure from another.
2215 * If fdp is not NULL, return with it shared locked.
2220 struct filedesc0 *newfdp0;
2221 struct filedesc *newfdp;
2223 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2224 newfdp = &newfdp0->fd_fd;
2226 /* Create the file descriptor table. */
2227 FILEDESC_LOCK_INIT(newfdp);
2228 refcount_init(&newfdp->fd_refcnt, 1);
2229 refcount_init(&newfdp->fd_holdcnt, 1);
2230 newfdp->fd_map = newfdp0->fd_dmap;
2231 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2232 newfdp->fd_files->fdt_nfiles = NDFILE;
2238 * Build a pwddesc structure from another.
2239 * Copy the current, root, and jail root vnode references.
2241 * If pdp is not NULL and keeplock is true, return with it (exclusively) locked.
2244 pdinit(struct pwddesc *pdp, bool keeplock)
2246 struct pwddesc *newpdp;
2249 newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2251 PWDDESC_LOCK_INIT(newpdp);
2252 refcount_init(&newpdp->pd_refcount, 1);
2253 newpdp->pd_cmask = CMASK;
2256 newpwd = pwd_alloc();
2257 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2262 newpwd = pwd_hold_pwddesc(pdp);
2263 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2265 PWDDESC_XUNLOCK(pdp);
2270 * Hold either filedesc or pwddesc of the passed process.
2272 * The process lock is used to synchronize against the target exiting and
2275 * Clearing can be ilustrated in 3 steps:
2276 * 1. set the pointer to NULL. Either routine can race against it, hence
2278 * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2279 * race to either still see the pointer or find NULL. It is still safe to
2280 * grab a reference as clearing is stalled.
2281 * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2282 * guaranteed to see NULL, making it safe to finish clearing
2284 static struct filedesc *
2285 fdhold(struct proc *p)
2287 struct filedesc *fdp;
2289 PROC_LOCK_ASSERT(p, MA_OWNED);
2290 fdp = atomic_load_ptr(&p->p_fd);
2292 refcount_acquire(&fdp->fd_holdcnt);
2296 static struct pwddesc *
2297 pdhold(struct proc *p)
2299 struct pwddesc *pdp;
2301 PROC_LOCK_ASSERT(p, MA_OWNED);
2302 pdp = atomic_load_ptr(&p->p_pd);
2304 refcount_acquire(&pdp->pd_refcount);
2309 fddrop(struct filedesc *fdp)
2312 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2313 if (refcount_release(&fdp->fd_holdcnt) == 0)
2317 FILEDESC_LOCK_DESTROY(fdp);
2318 uma_zfree(filedesc0_zone, fdp);
2322 pddrop(struct pwddesc *pdp)
2326 if (refcount_release_if_not_last(&pdp->pd_refcount))
2330 if (refcount_release(&pdp->pd_refcount) == 0) {
2331 PWDDESC_XUNLOCK(pdp);
2334 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2336 PWDDESC_XUNLOCK(pdp);
2339 PWDDESC_LOCK_DESTROY(pdp);
2340 free(pdp, M_PWDDESC);
2344 * Share a filedesc structure.
2347 fdshare(struct filedesc *fdp)
2350 refcount_acquire(&fdp->fd_refcnt);
2355 * Share a pwddesc structure.
2358 pdshare(struct pwddesc *pdp)
2360 refcount_acquire(&pdp->pd_refcount);
2365 * Unshare a filedesc structure, if necessary by making a copy
2368 fdunshare(struct thread *td)
2370 struct filedesc *tmp;
2371 struct proc *p = td->td_proc;
2373 if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2376 tmp = fdcopy(p->p_fd);
2382 * Unshare a pwddesc structure.
2385 pdunshare(struct thread *td)
2387 struct pwddesc *pdp;
2392 if (refcount_load(&p->p_pd->pd_refcount) == 1)
2395 pdp = pdcopy(p->p_pd);
2401 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2402 * this is to ease callers, not catch errors.
2405 fdcopy(struct filedesc *fdp)
2407 struct filedesc *newfdp;
2408 struct filedescent *nfde, *ofde;
2414 FILEDESC_SLOCK(fdp);
2416 lastfile = fdlastfile(fdp);
2417 if (lastfile < newfdp->fd_nfiles)
2419 FILEDESC_SUNLOCK(fdp);
2420 fdgrowtable(newfdp, lastfile + 1);
2421 FILEDESC_SLOCK(fdp);
2423 /* copy all passable descriptors (i.e. not kqueue) */
2424 newfdp->fd_freefile = fdp->fd_freefile;
2425 FILEDESC_FOREACH_FDE(fdp, i, ofde) {
2426 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2427 !fhold(ofde->fde_file)) {
2428 if (newfdp->fd_freefile == fdp->fd_freefile)
2429 newfdp->fd_freefile = i;
2432 nfde = &newfdp->fd_ofiles[i];
2434 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2435 fdused_init(newfdp, i);
2437 MPASS(newfdp->fd_freefile != -1);
2438 FILEDESC_SUNLOCK(fdp);
2443 * Copy a pwddesc structure.
2446 pdcopy(struct pwddesc *pdp)
2448 struct pwddesc *newpdp;
2452 newpdp = pdinit(pdp, true);
2453 newpdp->pd_cmask = pdp->pd_cmask;
2454 PWDDESC_XUNLOCK(pdp);
2459 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2460 * one of processes using it exits) and the table used to be shared.
2463 fdclearlocks(struct thread *td)
2465 struct filedesc *fdp;
2466 struct filedesc_to_leader *fdtol;
2476 MPASS(fdtol != NULL);
2478 FILEDESC_XLOCK(fdp);
2479 KASSERT(fdtol->fdl_refcount > 0,
2480 ("filedesc_to_refcount botch: fdl_refcount=%d",
2481 fdtol->fdl_refcount));
2482 if (fdtol->fdl_refcount == 1 &&
2483 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2484 FILEDESC_FOREACH_FP(fdp, i, fp) {
2485 if (fp->f_type != DTYPE_VNODE ||
2488 FILEDESC_XUNLOCK(fdp);
2489 lf.l_whence = SEEK_SET;
2492 lf.l_type = F_UNLCK;
2494 (void) VOP_ADVLOCK(vp,
2495 (caddr_t)p->p_leader, F_UNLCK,
2497 FILEDESC_XLOCK(fdp);
2502 if (fdtol->fdl_refcount == 1) {
2503 if (fdp->fd_holdleaderscount > 0 &&
2504 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2506 * close() or kern_dup() has cleared a reference
2507 * in a shared file descriptor table.
2509 fdp->fd_holdleaderswakeup = 1;
2510 sx_sleep(&fdp->fd_holdleaderscount,
2511 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2514 if (fdtol->fdl_holdcount > 0) {
2516 * Ensure that fdtol->fdl_leader remains
2517 * valid in closef().
2519 fdtol->fdl_wakeup = 1;
2520 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2525 fdtol->fdl_refcount--;
2526 if (fdtol->fdl_refcount == 0 &&
2527 fdtol->fdl_holdcount == 0) {
2528 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2529 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2533 FILEDESC_XUNLOCK(fdp);
2535 free(fdtol, M_FILEDESC_TO_LEADER);
2539 * Release a filedesc structure.
2542 fdescfree_fds(struct thread *td, struct filedesc *fdp)
2544 struct filedesc0 *fdp0;
2545 struct freetable *ft, *tft;
2546 struct filedescent *fde;
2550 KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2551 ("%s: fd table %p carries references", __func__, fdp));
2554 * Serialize with threads iterating over the table, if any.
2556 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2557 FILEDESC_XLOCK(fdp);
2558 FILEDESC_XUNLOCK(fdp);
2561 FILEDESC_FOREACH_FDE(fdp, i, fde) {
2564 (void) closef(fp, td);
2567 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2568 free(fdp->fd_map, M_FILEDESC);
2569 if (fdp->fd_nfiles > NDFILE)
2570 free(fdp->fd_files, M_FILEDESC);
2572 fdp0 = (struct filedesc0 *)fdp;
2573 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2574 free(ft->ft_table, M_FILEDESC);
2580 fdescfree(struct thread *td)
2583 struct filedesc *fdp;
2590 if (RACCT_ENABLED())
2591 racct_set_unlocked(p, RACCT_NOFILE, 0);
2594 if (p->p_fdtol != NULL)
2598 * Check fdhold for an explanation.
2600 atomic_store_ptr(&p->p_fd, NULL);
2601 atomic_thread_fence_seq_cst();
2602 PROC_WAIT_UNLOCKED(p);
2604 if (refcount_release(&fdp->fd_refcnt) == 0)
2607 fdescfree_fds(td, fdp);
2611 pdescfree(struct thread *td)
2614 struct pwddesc *pdp;
2621 * Check pdhold for an explanation.
2623 atomic_store_ptr(&p->p_pd, NULL);
2624 atomic_thread_fence_seq_cst();
2625 PROC_WAIT_UNLOCKED(p);
2631 * For setugid programs, we don't want to people to use that setugidness
2632 * to generate error messages which write to a file which otherwise would
2633 * otherwise be off-limits to the process. We check for filesystems where
2634 * the vnode can change out from under us after execve (like [lin]procfs).
2636 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2637 * sufficient. We also don't check for setugidness since we know we are.
2640 is_unsafe(struct file *fp)
2644 if (fp->f_type != DTYPE_VNODE)
2648 return ((vp->v_vflag & VV_PROCDEP) != 0);
2652 * Make this setguid thing safe, if at all possible.
2655 fdsetugidsafety(struct thread *td)
2657 struct filedesc *fdp;
2661 fdp = td->td_proc->p_fd;
2662 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2663 ("the fdtable should not be shared"));
2664 MPASS(fdp->fd_nfiles >= 3);
2665 for (i = 0; i <= 2; i++) {
2666 fp = fdp->fd_ofiles[i].fde_file;
2667 if (fp != NULL && is_unsafe(fp)) {
2668 FILEDESC_XLOCK(fdp);
2669 knote_fdclose(td, i);
2671 * NULL-out descriptor prior to close to avoid
2672 * a race while close blocks.
2675 FILEDESC_XUNLOCK(fdp);
2676 (void) closef(fp, td);
2682 * If a specific file object occupies a specific file descriptor, close the
2683 * file descriptor entry and drop a reference on the file object. This is a
2684 * convenience function to handle a subsequent error in a function that calls
2685 * falloc() that handles the race that another thread might have closed the
2686 * file descriptor out from under the thread creating the file object.
2689 fdclose(struct thread *td, struct file *fp, int idx)
2691 struct filedesc *fdp = td->td_proc->p_fd;
2693 FILEDESC_XLOCK(fdp);
2694 if (fdp->fd_ofiles[idx].fde_file == fp) {
2696 FILEDESC_XUNLOCK(fdp);
2699 FILEDESC_XUNLOCK(fdp);
2703 * Close any files on exec?
2706 fdcloseexec(struct thread *td)
2708 struct filedesc *fdp;
2709 struct filedescent *fde;
2713 fdp = td->td_proc->p_fd;
2714 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2715 ("the fdtable should not be shared"));
2716 FILEDESC_FOREACH_FDE(fdp, i, fde) {
2718 if (fp->f_type == DTYPE_MQUEUE ||
2719 (fde->fde_flags & UF_EXCLOSE)) {
2720 FILEDESC_XLOCK(fdp);
2722 (void) closefp(fdp, i, fp, td, false, false);
2723 FILEDESC_UNLOCK_ASSERT(fdp);
2729 * It is unsafe for set[ug]id processes to be started with file
2730 * descriptors 0..2 closed, as these descriptors are given implicit
2731 * significance in the Standard C library. fdcheckstd() will create a
2732 * descriptor referencing /dev/null for each of stdin, stdout, and
2733 * stderr that is not already open.
2736 fdcheckstd(struct thread *td)
2738 struct filedesc *fdp;
2740 int i, error, devnull;
2742 fdp = td->td_proc->p_fd;
2743 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2744 ("the fdtable should not be shared"));
2745 MPASS(fdp->fd_nfiles >= 3);
2747 for (i = 0; i <= 2; i++) {
2748 if (fdp->fd_ofiles[i].fde_file != NULL)
2751 save = td->td_retval[0];
2752 if (devnull != -1) {
2753 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2755 error = kern_openat(td, AT_FDCWD, "/dev/null",
2756 UIO_SYSSPACE, O_RDWR, 0);
2758 devnull = td->td_retval[0];
2759 KASSERT(devnull == i, ("we didn't get our fd"));
2762 td->td_retval[0] = save;
2770 * Internal form of close. Decrement reference count on file structure.
2771 * Note: td may be NULL when closing a file that was being passed in a
2775 closef(struct file *fp, struct thread *td)
2779 struct filedesc_to_leader *fdtol;
2780 struct filedesc *fdp;
2785 * POSIX record locking dictates that any close releases ALL
2786 * locks owned by this process. This is handled by setting
2787 * a flag in the unlock to free ONLY locks obeying POSIX
2788 * semantics, and not to free BSD-style file locks.
2789 * If the descriptor was in a message, POSIX-style locks
2790 * aren't passed with the descriptor, and the thread pointer
2791 * will be NULL. Callers should be careful only to pass a
2792 * NULL thread pointer when there really is no owning
2793 * context that might have locks, or the locks will be
2796 if (fp->f_type == DTYPE_VNODE) {
2798 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2799 lf.l_whence = SEEK_SET;
2802 lf.l_type = F_UNLCK;
2803 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2804 F_UNLCK, &lf, F_POSIX);
2806 fdtol = td->td_proc->p_fdtol;
2807 if (fdtol != NULL) {
2809 * Handle special case where file descriptor table is
2810 * shared between multiple process leaders.
2812 fdp = td->td_proc->p_fd;
2813 FILEDESC_XLOCK(fdp);
2814 for (fdtol = fdtol->fdl_next;
2815 fdtol != td->td_proc->p_fdtol;
2816 fdtol = fdtol->fdl_next) {
2817 if ((fdtol->fdl_leader->p_flag &
2820 fdtol->fdl_holdcount++;
2821 FILEDESC_XUNLOCK(fdp);
2822 lf.l_whence = SEEK_SET;
2825 lf.l_type = F_UNLCK;
2827 (void) VOP_ADVLOCK(vp,
2828 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2830 FILEDESC_XLOCK(fdp);
2831 fdtol->fdl_holdcount--;
2832 if (fdtol->fdl_holdcount == 0 &&
2833 fdtol->fdl_wakeup != 0) {
2834 fdtol->fdl_wakeup = 0;
2838 FILEDESC_XUNLOCK(fdp);
2841 return (fdrop_close(fp, td));
2845 * Hack for file descriptor passing code.
2848 closef_nothread(struct file *fp)
2855 * Initialize the file pointer with the specified properties.
2857 * The ops are set with release semantics to be certain that the flags, type,
2858 * and data are visible when ops is. This is to prevent ops methods from being
2859 * called with bad data.
2862 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2867 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2871 finit_vnode(struct file *fp, u_int flag, void *data, struct fileops *ops)
2873 fp->f_seqcount[UIO_READ] = 1;
2874 fp->f_seqcount[UIO_WRITE] = 1;
2875 finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2880 fget_cap_noref(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2881 struct file **fpp, struct filecaps *havecapsp)
2883 struct filedescent *fde;
2886 FILEDESC_LOCK_ASSERT(fdp);
2889 fde = fdeget_noref(fdp, fd);
2896 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2901 if (havecapsp != NULL)
2902 filecaps_copy(&fde->fde_caps, havecapsp, true);
2904 *fpp = fde->fde_file;
2913 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2914 struct file **fpp, struct filecaps *havecapsp)
2916 struct filedesc *fdp = td->td_proc->p_fd;
2923 error = fget_unlocked_seq(td, fd, needrightsp, &fp, &seq);
2927 if (havecapsp != NULL) {
2928 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2929 havecapsp, false)) {
2935 if (!fd_modified(fdp, fd, seq))
2944 FILEDESC_SLOCK(fdp);
2945 error = fget_cap_noref(fdp, fd, needrightsp, fpp, havecapsp);
2946 if (error == 0 && !fhold(*fpp))
2948 FILEDESC_SUNLOCK(fdp);
2953 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2954 struct file **fpp, struct filecaps *havecapsp)
2957 error = fget_unlocked(td, fd, needrightsp, fpp);
2958 if (havecapsp != NULL && error == 0)
2959 filecaps_fill(havecapsp);
2967 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
2969 const struct filedescent *fde;
2970 const struct fdescenttbl *fdt;
2971 struct filedesc *fdp;
2974 const cap_rights_t *haverights;
2975 cap_rights_t rights;
2978 VFS_SMR_ASSERT_ENTERED();
2980 rights = *ndp->ni_rightsneeded;
2981 cap_rights_set_one(&rights, CAP_LOOKUP);
2983 fdp = curproc->p_fd;
2984 fdt = fdp->fd_files;
2985 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2987 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
2988 fde = &fdt->fdt_ofiles[fd];
2989 haverights = cap_rights_fde_inline(fde);
2991 if (__predict_false(fp == NULL))
2993 if (__predict_false(cap_check_inline_transient(haverights, &rights)))
2995 *fsearch = ((fp->f_flag & FSEARCH) != 0);
2997 if (__predict_false(vp == NULL)) {
3000 if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
3004 * Use an acquire barrier to force re-reading of fdt so it is
3005 * refreshed for verification.
3007 atomic_thread_fence_acq();
3008 fdt = fdp->fd_files;
3009 if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3012 * If file descriptor doesn't have all rights,
3013 * all lookups relative to it must also be
3014 * strictly relative.
3016 * Not yet supported by fast path.
3019 if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3020 ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3021 ndp->ni_filecaps.fc_nioctls != -1) {
3023 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
3033 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3035 const struct fdescenttbl *fdt;
3036 struct filedesc *fdp;
3040 VFS_SMR_ASSERT_ENTERED();
3042 fdp = curproc->p_fd;
3043 fdt = fdp->fd_files;
3044 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3046 fp = fdt->fdt_ofiles[fd].fde_file;
3047 if (__predict_false(fp == NULL))
3049 *fsearch = ((fp->f_flag & FSEARCH) != 0);
3051 if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
3055 * Use an acquire barrier to force re-reading of fdt so it is
3056 * refreshed for verification.
3058 atomic_thread_fence_acq();
3059 fdt = fdp->fd_files;
3060 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3062 filecaps_fill(&ndp->ni_filecaps);
3069 fgetvp_lookup(int fd, struct nameidata *ndp, struct vnode **vpp)
3074 struct componentname *cnp;
3075 cap_rights_t rights;
3079 rights = *ndp->ni_rightsneeded;
3080 cap_rights_set_one(&rights, CAP_LOOKUP);
3083 error = fget_cap(td, ndp->ni_dirfd, &rights, &fp, &ndp->ni_filecaps);
3084 if (__predict_false(error != 0))
3086 if (__predict_false(fp->f_ops == &badfileops)) {
3091 if (__predict_false(vp == NULL)) {
3097 * XXX does not check for VDIR, handled by namei_setup
3099 if ((fp->f_flag & FSEARCH) != 0)
3100 cnp->cn_flags |= NOEXECCHECK;
3105 * If file descriptor doesn't have all rights,
3106 * all lookups relative to it must also be
3107 * strictly relative.
3110 if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3111 ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3112 ndp->ni_filecaps.fc_nioctls != -1) {
3113 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
3114 ndp->ni_resflags |= NIRES_STRICTREL;
3119 * TODO: avoid copying ioctl caps if it can be helped to begin with
3121 if ((cnp->cn_flags & WANTIOCTLCAPS) == 0)
3122 filecaps_free_ioctl(&ndp->ni_filecaps);
3128 filecaps_free(&ndp->ni_filecaps);
3134 * Fetch the descriptor locklessly.
3136 * We avoid fdrop() races by never raising a refcount above 0. To accomplish
3137 * this we have to use a cmpset loop rather than an atomic_add. The descriptor
3138 * must be re-verified once we acquire a reference to be certain that the
3139 * identity is still correct and we did not lose a race due to preemption.
3141 * Force a reload of fdt when looping. Another thread could reallocate
3142 * the table before this fd was closed, so it is possible that there is
3143 * a stale fp pointer in cached version.
3147 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3148 struct file **fpp, seqc_t *seqp)
3150 struct filedesc *fdp;
3151 const struct filedescent *fde;
3152 const struct fdescenttbl *fdt;
3155 cap_rights_t haverights;
3158 fdp = td->td_proc->p_fd;
3159 fdt = fdp->fd_files;
3160 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3164 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3165 fde = &fdt->fdt_ofiles[fd];
3166 haverights = *cap_rights_fde_inline(fde);
3168 if (__predict_false(fp == NULL)) {
3169 if (seqc_consistent(fd_seqc(fdt, fd), seq))
3171 fdt = atomic_load_ptr(&fdp->fd_files);
3174 error = cap_check_inline(&haverights, needrightsp);
3175 if (__predict_false(error != 0)) {
3176 if (seqc_consistent(fd_seqc(fdt, fd), seq))
3178 fdt = atomic_load_ptr(&fdp->fd_files);
3181 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3182 fdt = atomic_load_ptr(&fdp->fd_files);
3186 * Use an acquire barrier to force re-reading of fdt so it is
3187 * refreshed for verification.
3189 atomic_thread_fence_acq();
3190 fdt = fdp->fd_files;
3191 if (seqc_consistent_no_fence(fd_seqc(fdt, fd), seq))
3203 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3204 struct file **fpp, seqc_t *seqp __unused)
3206 struct filedesc *fdp;
3207 const struct fdescenttbl *fdt;
3210 fdp = td->td_proc->p_fd;
3211 fdt = fdp->fd_files;
3212 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3216 fp = fdt->fdt_ofiles[fd].fde_file;
3217 if (__predict_false(fp == NULL))
3219 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3220 fdt = atomic_load_ptr(&fdp->fd_files);
3224 * Use an acquire barrier to force re-reading of fdt so it is
3225 * refreshed for verification.
3227 atomic_thread_fence_acq();
3228 fdt = fdp->fd_files;
3229 if (__predict_true(fp == fdt->fdt_ofiles[fd].fde_file))
3239 * See the comments in fget_unlocked_seq for an explanation of how this works.
3241 * This is a simplified variant which bails out to the aforementioned routine
3242 * if anything goes wrong. In practice this only happens when userspace is
3243 * racing with itself.
3246 fget_unlocked(struct thread *td, int fd, cap_rights_t *needrightsp,
3249 struct filedesc *fdp;
3251 const struct filedescent *fde;
3253 const struct fdescenttbl *fdt;
3257 const cap_rights_t *haverights;
3260 fdp = td->td_proc->p_fd;
3261 fdt = fdp->fd_files;
3262 if (__predict_false((u_int)fd >= fdt->fdt_nfiles)) {
3267 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3268 fde = &fdt->fdt_ofiles[fd];
3269 haverights = cap_rights_fde_inline(fde);
3272 fp = fdt->fdt_ofiles[fd].fde_file;
3274 if (__predict_false(fp == NULL))
3277 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3280 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3284 * Use an acquire barrier to force re-reading of fdt so it is
3285 * refreshed for verification.
3287 atomic_thread_fence_acq();
3288 fdt = fdp->fd_files;
3290 if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3292 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3301 return (fget_unlocked_seq(td, fd, needrightsp, fpp, NULL));
3305 * Translate fd -> file when the caller guarantees the file descriptor table
3306 * can't be changed by others.
3308 * Note this does not mean the file object itself is only visible to the caller,
3309 * merely that it wont disappear without having to be referenced.
3311 * Must be paired with fput_only_user.
3315 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3318 const struct filedescent *fde;
3319 const struct fdescenttbl *fdt;
3320 const cap_rights_t *haverights;
3324 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3327 if (__predict_false(fd >= fdp->fd_nfiles))
3330 fdt = fdp->fd_files;
3331 fde = &fdt->fdt_ofiles[fd];
3333 if (__predict_false(fp == NULL))
3335 MPASS(refcount_load(&fp->f_count) > 0);
3336 haverights = cap_rights_fde_inline(fde);
3337 error = cap_check_inline(haverights, needrightsp);
3338 if (__predict_false(error != 0))
3345 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3350 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3353 if (__predict_false(fd >= fdp->fd_nfiles))
3356 fp = fdp->fd_ofiles[fd].fde_file;
3357 if (__predict_false(fp == NULL))
3360 MPASS(refcount_load(&fp->f_count) > 0);
3367 * Extract the file pointer associated with the specified descriptor for the
3368 * current user process.
3370 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3373 * File's rights will be checked against the capability rights mask.
3375 * If an error occurred the non-zero error is returned and *fpp is set to
3376 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
3377 * responsible for fdrop().
3380 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3381 cap_rights_t *needrightsp)
3387 error = fget_unlocked(td, fd, needrightsp, &fp);
3388 if (__predict_false(error != 0))
3390 if (__predict_false(fp->f_ops == &badfileops)) {
3396 * FREAD and FWRITE failure return EBADF as per POSIX.
3402 if ((fp->f_flag & flags) == 0)
3406 if (fp->f_ops != &path_fileops &&
3407 ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3408 (fp->f_flag & FWRITE) != 0))
3414 KASSERT(0, ("wrong flags"));
3427 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3430 return (_fget(td, fd, fpp, 0, rightsp));
3434 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
3438 #ifndef CAPABILITIES
3439 error = _fget(td, fd, fpp, 0, rightsp);
3440 if (maxprotp != NULL)
3441 *maxprotp = VM_PROT_ALL;
3444 cap_rights_t fdrights;
3445 struct filedesc *fdp;
3450 fdp = td->td_proc->p_fd;
3451 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3453 error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3454 if (__predict_false(error != 0))
3456 if (__predict_false(fp->f_ops == &badfileops)) {
3460 if (maxprotp != NULL)
3461 fdrights = *cap_rights(fdp, fd);
3462 if (!fd_modified(fdp, fd, seq))
3468 * If requested, convert capability rights to access flags.
3470 if (maxprotp != NULL)
3471 *maxprotp = cap_rights_to_vmprot(&fdrights);
3478 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3481 return (_fget(td, fd, fpp, FREAD, rightsp));
3485 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3488 return (_fget(td, fd, fpp, FWRITE, rightsp));
3492 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
3495 #ifndef CAPABILITIES
3496 return (fget_unlocked(td, fd, rightsp, fpp));
3498 struct filedesc *fdp = td->td_proc->p_fd;
3504 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3506 error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3509 error = cap_fcntl_check(fdp, fd, needfcntl);
3510 if (!fd_modified(fdp, fd, seq))
3524 * Like fget() but loads the underlying vnode, or returns an error if the
3525 * descriptor does not represent a vnode. Note that pipes use vnodes but
3526 * never have VM objects. The returned vnode will be vref()'d.
3528 * XXX: what about the unused flags ?
3531 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3538 error = _fget(td, fd, &fp, flags, needrightsp);
3541 if (fp->f_vnode == NULL) {
3553 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3556 return (_fgetvp(td, fd, 0, rightsp, vpp));
3560 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3561 struct filecaps *havecaps, struct vnode **vpp)
3563 struct filecaps caps;
3567 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3570 if (fp->f_ops == &badfileops) {
3574 if (fp->f_vnode == NULL) {
3586 filecaps_free(&caps);
3592 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3595 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3599 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3602 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3607 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3611 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3616 * Handle the last reference to a file being closed.
3618 * Without the noinline attribute clang keeps inlining the func thorough this
3619 * file when fdrop is used.
3622 _fdrop(struct file *fp, struct thread *td)
3628 count = refcount_load(&fp->f_count);
3630 panic("fdrop: fp %p count %d", fp, count);
3632 error = fo_close(fp, td);
3633 atomic_subtract_int(&openfiles, 1);
3635 free(fp->f_advice, M_FADVISE);
3636 uma_zfree(file_zone, fp);
3642 * Apply an advisory lock on a file descriptor.
3644 * Just attempt to get a record lock of the requested type on the entire file
3645 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3647 #ifndef _SYS_SYSPROTO_H_
3655 sys_flock(struct thread *td, struct flock_args *uap)
3662 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3666 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3669 if (fp->f_ops == &path_fileops) {
3675 lf.l_whence = SEEK_SET;
3678 if (uap->how & LOCK_UN) {
3679 lf.l_type = F_UNLCK;
3680 atomic_clear_int(&fp->f_flag, FHASLOCK);
3681 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3684 if (uap->how & LOCK_EX)
3685 lf.l_type = F_WRLCK;
3686 else if (uap->how & LOCK_SH)
3687 lf.l_type = F_RDLCK;
3692 atomic_set_int(&fp->f_flag, FHASLOCK);
3693 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3694 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3700 * Duplicate the specified descriptor to a free descriptor.
3703 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3704 int openerror, int *indxp)
3706 struct filedescent *newfde, *oldfde;
3711 KASSERT(openerror == ENODEV || openerror == ENXIO,
3712 ("unexpected error %d in %s", openerror, __func__));
3715 * If the to-be-dup'd fd number is greater than the allowed number
3716 * of file descriptors, or the fd to be dup'd has already been
3717 * closed, then reject.
3719 FILEDESC_XLOCK(fdp);
3720 if ((fp = fget_noref(fdp, dfd)) == NULL) {
3721 FILEDESC_XUNLOCK(fdp);
3725 error = fdalloc(td, 0, &indx);
3727 FILEDESC_XUNLOCK(fdp);
3732 * There are two cases of interest here.
3734 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3736 * For ENXIO steal away the file structure from (dfd) and store it in
3737 * (indx). (dfd) is effectively closed by this operation.
3739 switch (openerror) {
3742 * Check that the mode the file is being opened for is a
3743 * subset of the mode of the existing descriptor.
3745 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3746 fdunused(fdp, indx);
3747 FILEDESC_XUNLOCK(fdp);
3751 fdunused(fdp, indx);
3752 FILEDESC_XUNLOCK(fdp);
3755 newfde = &fdp->fd_ofiles[indx];
3756 oldfde = &fdp->fd_ofiles[dfd];
3757 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3759 seqc_write_begin(&newfde->fde_seqc);
3761 fde_copy(oldfde, newfde);
3762 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3765 seqc_write_end(&newfde->fde_seqc);
3770 * Steal away the file pointer from dfd and stuff it into indx.
3772 newfde = &fdp->fd_ofiles[indx];
3773 oldfde = &fdp->fd_ofiles[dfd];
3775 seqc_write_begin(&oldfde->fde_seqc);
3776 seqc_write_begin(&newfde->fde_seqc);
3778 fde_copy(oldfde, newfde);
3779 oldfde->fde_file = NULL;
3782 seqc_write_end(&newfde->fde_seqc);
3783 seqc_write_end(&oldfde->fde_seqc);
3787 FILEDESC_XUNLOCK(fdp);
3793 * This sysctl determines if we will allow a process to chroot(2) if it
3794 * has a directory open:
3795 * 0: disallowed for all processes.
3796 * 1: allowed for processes that were not already chroot(2)'ed.
3797 * 2: allowed for all processes.
3800 static int chroot_allow_open_directories = 1;
3802 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3803 &chroot_allow_open_directories, 0,
3804 "Allow a process to chroot(2) if it has a directory open");
3807 * Helper function for raised chroot(2) security function: Refuse if
3808 * any filedescriptors are open directories.
3811 chroot_refuse_vdir_fds(struct filedesc *fdp)
3817 FILEDESC_LOCK_ASSERT(fdp);
3819 FILEDESC_FOREACH_FP(fdp, i, fp) {
3820 if (fp->f_type == DTYPE_VNODE) {
3822 if (vp->v_type == VDIR)
3830 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3833 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3834 vrefact(oldpwd->pwd_cdir);
3835 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3838 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3839 vrefact(oldpwd->pwd_rdir);
3840 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3843 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3844 vrefact(oldpwd->pwd_jdir);
3845 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3848 if (newpwd->pwd_adir == NULL && oldpwd->pwd_adir != NULL) {
3849 vrefact(oldpwd->pwd_adir);
3850 newpwd->pwd_adir = oldpwd->pwd_adir;
3855 pwd_hold_pwddesc(struct pwddesc *pdp)
3859 PWDDESC_ASSERT_XLOCKED(pdp);
3860 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3862 refcount_acquire(&pwd->pwd_refcount);
3867 pwd_hold_smr(struct pwd *pwd)
3871 if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3878 pwd_hold(struct thread *td)
3880 struct pwddesc *pdp;
3883 pdp = td->td_proc->p_pd;
3886 pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3887 if (pwd_hold_smr(pwd)) {
3893 pwd = pwd_hold_pwddesc(pdp);
3895 PWDDESC_XUNLOCK(pdp);
3900 pwd_hold_proc(struct proc *p)
3902 struct pwddesc *pdp;
3905 PROC_ASSERT_HELD(p);
3912 pwd = pwd_hold_pwddesc(pdp);
3914 PWDDESC_XUNLOCK(pdp);
3924 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3925 bzero(pwd, sizeof(*pwd));
3926 refcount_init(&pwd->pwd_refcount, 1);
3931 pwd_drop(struct pwd *pwd)
3934 if (!refcount_release(&pwd->pwd_refcount))
3937 if (pwd->pwd_cdir != NULL)
3938 vrele(pwd->pwd_cdir);
3939 if (pwd->pwd_rdir != NULL)
3940 vrele(pwd->pwd_rdir);
3941 if (pwd->pwd_jdir != NULL)
3942 vrele(pwd->pwd_jdir);
3943 if (pwd->pwd_adir != NULL)
3944 vrele(pwd->pwd_adir);
3945 uma_zfree_smr(pwd_zone, pwd);
3949 * The caller is responsible for invoking priv_check() and
3950 * mac_vnode_check_chroot() to authorize this operation.
3953 pwd_chroot(struct thread *td, struct vnode *vp)
3955 struct pwddesc *pdp;
3956 struct filedesc *fdp;
3957 struct pwd *newpwd, *oldpwd;
3960 fdp = td->td_proc->p_fd;
3961 pdp = td->td_proc->p_pd;
3962 newpwd = pwd_alloc();
3963 FILEDESC_SLOCK(fdp);
3965 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3966 if (chroot_allow_open_directories == 0 ||
3967 (chroot_allow_open_directories == 1 &&
3968 oldpwd->pwd_rdir != rootvnode)) {
3969 error = chroot_refuse_vdir_fds(fdp);
3970 FILEDESC_SUNLOCK(fdp);
3972 PWDDESC_XUNLOCK(pdp);
3977 FILEDESC_SUNLOCK(fdp);
3981 newpwd->pwd_rdir = vp;
3983 newpwd->pwd_adir = vp;
3984 if (oldpwd->pwd_jdir == NULL) {
3986 newpwd->pwd_jdir = vp;
3988 pwd_fill(oldpwd, newpwd);
3989 pwd_set(pdp, newpwd);
3990 PWDDESC_XUNLOCK(pdp);
3996 pwd_chdir(struct thread *td, struct vnode *vp)
3998 struct pwddesc *pdp;
3999 struct pwd *newpwd, *oldpwd;
4001 VNPASS(vp->v_usecount > 0, vp);
4003 newpwd = pwd_alloc();
4004 pdp = td->td_proc->p_pd;
4006 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4007 newpwd->pwd_cdir = vp;
4008 pwd_fill(oldpwd, newpwd);
4009 pwd_set(pdp, newpwd);
4010 PWDDESC_XUNLOCK(pdp);
4015 * Process is transitioning to/from a non-native ABI.
4018 pwd_altroot(struct thread *td, struct vnode *altroot_vp)
4020 struct pwddesc *pdp;
4021 struct pwd *newpwd, *oldpwd;
4023 newpwd = pwd_alloc();
4024 pdp = td->td_proc->p_pd;
4026 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4027 if (altroot_vp != NULL) {
4029 * Native process to a non-native ABI.
4032 vrefact(altroot_vp);
4033 newpwd->pwd_adir = altroot_vp;
4036 * Non-native process to the native ABI.
4039 vrefact(oldpwd->pwd_rdir);
4040 newpwd->pwd_adir = oldpwd->pwd_rdir;
4042 pwd_fill(oldpwd, newpwd);
4043 pwd_set(pdp, newpwd);
4044 PWDDESC_XUNLOCK(pdp);
4049 * jail_attach(2) changes both root and working directories.
4052 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
4054 struct pwddesc *pdp;
4055 struct filedesc *fdp;
4056 struct pwd *newpwd, *oldpwd;
4059 fdp = td->td_proc->p_fd;
4060 pdp = td->td_proc->p_pd;
4061 newpwd = pwd_alloc();
4062 FILEDESC_SLOCK(fdp);
4064 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4065 error = chroot_refuse_vdir_fds(fdp);
4066 FILEDESC_SUNLOCK(fdp);
4068 PWDDESC_XUNLOCK(pdp);
4074 newpwd->pwd_rdir = vp;
4076 newpwd->pwd_cdir = vp;
4077 if (oldpwd->pwd_jdir == NULL) {
4079 newpwd->pwd_jdir = vp;
4082 newpwd->pwd_adir = vp;
4083 pwd_fill(oldpwd, newpwd);
4084 pwd_set(pdp, newpwd);
4085 PWDDESC_XUNLOCK(pdp);
4091 pwd_ensure_dirs(void)
4093 struct pwddesc *pdp;
4094 struct pwd *oldpwd, *newpwd;
4096 pdp = curproc->p_pd;
4098 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4099 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL &&
4100 oldpwd->pwd_adir != NULL) {
4101 PWDDESC_XUNLOCK(pdp);
4104 PWDDESC_XUNLOCK(pdp);
4106 newpwd = pwd_alloc();
4108 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4109 pwd_fill(oldpwd, newpwd);
4110 if (newpwd->pwd_cdir == NULL) {
4112 newpwd->pwd_cdir = rootvnode;
4114 if (newpwd->pwd_rdir == NULL) {
4116 newpwd->pwd_rdir = rootvnode;
4118 if (newpwd->pwd_adir == NULL) {
4120 newpwd->pwd_adir = rootvnode;
4122 pwd_set(pdp, newpwd);
4123 PWDDESC_XUNLOCK(pdp);
4128 pwd_set_rootvnode(void)
4130 struct pwddesc *pdp;
4131 struct pwd *oldpwd, *newpwd;
4133 pdp = curproc->p_pd;
4135 newpwd = pwd_alloc();
4137 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4139 newpwd->pwd_cdir = rootvnode;
4141 newpwd->pwd_rdir = rootvnode;
4143 newpwd->pwd_adir = rootvnode;
4144 pwd_fill(oldpwd, newpwd);
4145 pwd_set(pdp, newpwd);
4146 PWDDESC_XUNLOCK(pdp);
4151 * Scan all active processes and prisons to see if any of them have a current
4152 * or root directory of `olddp'. If so, replace them with the new mount point.
4155 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
4157 struct pwddesc *pdp;
4158 struct pwd *newpwd, *oldpwd;
4163 if (vrefcnt(olddp) == 1)
4166 newpwd = pwd_alloc();
4167 sx_slock(&allproc_lock);
4168 FOREACH_PROC_IN_SYSTEM(p) {
4175 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4176 if (oldpwd == NULL ||
4177 (oldpwd->pwd_cdir != olddp &&
4178 oldpwd->pwd_rdir != olddp &&
4179 oldpwd->pwd_jdir != olddp &&
4180 oldpwd->pwd_adir != olddp)) {
4181 PWDDESC_XUNLOCK(pdp);
4185 if (oldpwd->pwd_cdir == olddp) {
4187 newpwd->pwd_cdir = newdp;
4189 if (oldpwd->pwd_rdir == olddp) {
4191 newpwd->pwd_rdir = newdp;
4193 if (oldpwd->pwd_jdir == olddp) {
4195 newpwd->pwd_jdir = newdp;
4197 if (oldpwd->pwd_adir == olddp) {
4199 newpwd->pwd_adir = newdp;
4201 pwd_fill(oldpwd, newpwd);
4202 pwd_set(pdp, newpwd);
4203 PWDDESC_XUNLOCK(pdp);
4206 newpwd = pwd_alloc();
4208 sx_sunlock(&allproc_lock);
4210 if (rootvnode == olddp) {
4215 mtx_lock(&prison0.pr_mtx);
4216 if (prison0.pr_root == olddp) {
4218 prison0.pr_root = newdp;
4221 mtx_unlock(&prison0.pr_mtx);
4222 sx_slock(&allprison_lock);
4223 TAILQ_FOREACH(pr, &allprison, pr_list) {
4224 mtx_lock(&pr->pr_mtx);
4225 if (pr->pr_root == olddp) {
4227 pr->pr_root = newdp;
4230 mtx_unlock(&pr->pr_mtx);
4232 sx_sunlock(&allprison_lock);
4238 descrip_check_write_mp(struct filedesc *fdp, struct mount *mp)
4245 FILEDESC_SLOCK(fdp);
4246 FILEDESC_FOREACH_FP(fdp, i, fp) {
4247 if (fp->f_type != DTYPE_VNODE ||
4248 (atomic_load_int(&fp->f_flag) & FWRITE) == 0)
4251 if (vp->v_mount == mp) {
4256 FILEDESC_SUNLOCK(fdp);
4260 struct filedesc_to_leader *
4261 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp,
4262 struct proc *leader)
4264 struct filedesc_to_leader *fdtol;
4266 fdtol = malloc(sizeof(struct filedesc_to_leader),
4267 M_FILEDESC_TO_LEADER, M_WAITOK);
4268 fdtol->fdl_refcount = 1;
4269 fdtol->fdl_holdcount = 0;
4270 fdtol->fdl_wakeup = 0;
4271 fdtol->fdl_leader = leader;
4273 FILEDESC_XLOCK(fdp);
4274 fdtol->fdl_next = old->fdl_next;
4275 fdtol->fdl_prev = old;
4276 old->fdl_next = fdtol;
4277 fdtol->fdl_next->fdl_prev = fdtol;
4278 FILEDESC_XUNLOCK(fdp);
4280 fdtol->fdl_next = fdtol;
4281 fdtol->fdl_prev = fdtol;
4286 struct filedesc_to_leader *
4287 filedesc_to_leader_share(struct filedesc_to_leader *fdtol, struct filedesc *fdp)
4289 FILEDESC_XLOCK(fdp);
4290 fdtol->fdl_refcount++;
4291 FILEDESC_XUNLOCK(fdp);
4296 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4299 struct filedesc *fdp;
4301 int count, off, minoff;
4307 if (*(int *)arg1 != 0)
4310 fdp = curproc->p_fd;
4312 FILEDESC_SLOCK(fdp);
4314 off = NDSLOT(fdp->fd_nfiles - 1);
4315 for (minoff = NDSLOT(0); off >= minoff; --off)
4316 count += bitcountl(map[off]);
4317 FILEDESC_SUNLOCK(fdp);
4319 return (SYSCTL_OUT(req, &count, sizeof(count)));
4322 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4323 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4324 "Number of open file descriptors");
4327 * Get file structures globally.
4330 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4333 struct filedesc *fdp;
4338 error = sysctl_wire_old_buffer(req, 0);
4341 if (req->oldptr == NULL) {
4343 sx_slock(&allproc_lock);
4344 FOREACH_PROC_IN_SYSTEM(p) {
4346 if (p->p_state == PRS_NEW) {
4354 /* overestimates sparse tables. */
4355 n += fdp->fd_nfiles;
4358 sx_sunlock(&allproc_lock);
4359 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4362 bzero(&xf, sizeof(xf));
4363 xf.xf_size = sizeof(xf);
4364 sx_slock(&allproc_lock);
4365 FOREACH_PROC_IN_SYSTEM(p) {
4367 if (p->p_state == PRS_NEW) {
4371 if (p_cansee(req->td, p) != 0) {
4375 xf.xf_pid = p->p_pid;
4376 xf.xf_uid = p->p_ucred->cr_uid;
4381 FILEDESC_SLOCK(fdp);
4382 if (refcount_load(&fdp->fd_refcnt) == 0)
4384 FILEDESC_FOREACH_FP(fdp, n, fp) {
4386 xf.xf_file = (uintptr_t)fp;
4387 xf.xf_data = (uintptr_t)fp->f_data;
4388 xf.xf_vnode = (uintptr_t)fp->f_vnode;
4389 xf.xf_type = (uintptr_t)fp->f_type;
4390 xf.xf_count = refcount_load(&fp->f_count);
4392 xf.xf_offset = foffset_get(fp);
4393 xf.xf_flag = fp->f_flag;
4394 error = SYSCTL_OUT(req, &xf, sizeof(xf));
4397 * There is no need to re-check the fdtable refcount
4398 * here since the filedesc lock is not dropped in the
4405 FILEDESC_SUNLOCK(fdp);
4410 sx_sunlock(&allproc_lock);
4414 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4415 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4417 #ifdef KINFO_FILE_SIZE
4418 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4422 xlate_fflags(int fflags)
4424 static const struct {
4427 } fflags_table[] = {
4428 { FAPPEND, KF_FLAG_APPEND },
4429 { FASYNC, KF_FLAG_ASYNC },
4430 { FFSYNC, KF_FLAG_FSYNC },
4431 { FHASLOCK, KF_FLAG_HASLOCK },
4432 { FNONBLOCK, KF_FLAG_NONBLOCK },
4433 { FREAD, KF_FLAG_READ },
4434 { FWRITE, KF_FLAG_WRITE },
4435 { O_CREAT, KF_FLAG_CREAT },
4436 { O_DIRECT, KF_FLAG_DIRECT },
4437 { O_EXCL, KF_FLAG_EXCL },
4438 { O_EXEC, KF_FLAG_EXEC },
4439 { O_EXLOCK, KF_FLAG_EXLOCK },
4440 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4441 { O_SHLOCK, KF_FLAG_SHLOCK },
4442 { O_TRUNC, KF_FLAG_TRUNC }
4448 for (i = 0; i < nitems(fflags_table); i++)
4449 if (fflags & fflags_table[i].fflag)
4450 kflags |= fflags_table[i].kf_fflag;
4454 /* Trim unused data from kf_path by truncating the structure size. */
4456 pack_kinfo(struct kinfo_file *kif)
4459 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4460 strlen(kif->kf_path) + 1;
4461 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4465 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4466 struct kinfo_file *kif, struct filedesc *fdp, int flags)
4470 bzero(kif, sizeof(*kif));
4472 /* Set a default type to allow for empty fill_kinfo() methods. */
4473 kif->kf_type = KF_TYPE_UNKNOWN;
4474 kif->kf_flags = xlate_fflags(fp->f_flag);
4475 if (rightsp != NULL)
4476 kif->kf_cap_rights = *rightsp;
4478 cap_rights_init_zero(&kif->kf_cap_rights);
4480 kif->kf_ref_count = refcount_load(&fp->f_count);
4481 kif->kf_offset = foffset_get(fp);
4484 * This may drop the filedesc lock, so the 'fp' cannot be
4485 * accessed after this call.
4487 error = fo_fill_kinfo(fp, kif, fdp);
4489 kif->kf_status |= KF_ATTR_VALID;
4490 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4493 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4497 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4498 struct kinfo_file *kif, int flags)
4502 bzero(kif, sizeof(*kif));
4504 kif->kf_type = KF_TYPE_VNODE;
4505 error = vn_fill_kinfo_vnode(vp, kif);
4507 kif->kf_status |= KF_ATTR_VALID;
4508 kif->kf_flags = xlate_fflags(fflags);
4509 cap_rights_init_zero(&kif->kf_cap_rights);
4511 kif->kf_ref_count = -1;
4512 kif->kf_offset = -1;
4513 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4516 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4520 struct export_fd_buf {
4521 struct filedesc *fdp;
4522 struct pwddesc *pdp;
4525 struct kinfo_file kif;
4530 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4532 struct kinfo_file *kif;
4535 if (efbuf->remainder != -1) {
4536 if (efbuf->remainder < kif->kf_structsize)
4538 efbuf->remainder -= kif->kf_structsize;
4540 if (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) != 0)
4541 return (sbuf_error(efbuf->sb));
4546 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4547 struct export_fd_buf *efbuf)
4551 if (efbuf->remainder == 0)
4553 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4555 FILEDESC_SUNLOCK(efbuf->fdp);
4556 error = export_kinfo_to_sb(efbuf);
4557 FILEDESC_SLOCK(efbuf->fdp);
4562 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4563 struct export_fd_buf *efbuf)
4567 if (efbuf->remainder == 0)
4569 if (efbuf->pdp != NULL)
4570 PWDDESC_XUNLOCK(efbuf->pdp);
4571 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4572 error = export_kinfo_to_sb(efbuf);
4573 if (efbuf->pdp != NULL)
4574 PWDDESC_XLOCK(efbuf->pdp);
4579 * Store a process file descriptor information to sbuf.
4581 * Takes a locked proc as argument, and returns with the proc unlocked.
4584 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
4588 struct filedesc *fdp;
4589 struct pwddesc *pdp;
4590 struct export_fd_buf *efbuf;
4591 struct vnode *cttyvp, *textvp, *tracevp;
4594 cap_rights_t rights;
4596 PROC_LOCK_ASSERT(p, MA_OWNED);
4599 tracevp = ktr_get_tracevp(p, true);
4601 textvp = p->p_textvp;
4604 /* Controlling tty. */
4606 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4607 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4615 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4619 efbuf->remainder = maxlen;
4620 efbuf->flags = flags;
4623 if (tracevp != NULL)
4624 error = export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE,
4625 FREAD | FWRITE, efbuf);
4626 if (error == 0 && textvp != NULL)
4627 error = export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD,
4629 if (error == 0 && cttyvp != NULL)
4630 error = export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY,
4631 FREAD | FWRITE, efbuf);
4632 if (error != 0 || pdp == NULL || fdp == NULL)
4637 pwd = pwd_hold_pwddesc(pdp);
4639 /* working directory */
4640 if (pwd->pwd_cdir != NULL) {
4641 vrefact(pwd->pwd_cdir);
4642 error = export_vnode_to_sb(pwd->pwd_cdir,
4643 KF_FD_TYPE_CWD, FREAD, efbuf);
4645 /* root directory */
4646 if (error == 0 && pwd->pwd_rdir != NULL) {
4647 vrefact(pwd->pwd_rdir);
4648 error = export_vnode_to_sb(pwd->pwd_rdir,
4649 KF_FD_TYPE_ROOT, FREAD, efbuf);
4651 /* jail directory */
4652 if (error == 0 && pwd->pwd_jdir != NULL) {
4653 vrefact(pwd->pwd_jdir);
4654 error = export_vnode_to_sb(pwd->pwd_jdir,
4655 KF_FD_TYPE_JAIL, FREAD, efbuf);
4658 PWDDESC_XUNLOCK(pdp);
4663 FILEDESC_SLOCK(fdp);
4664 if (refcount_load(&fdp->fd_refcnt) == 0)
4666 FILEDESC_FOREACH_FP(fdp, i, fp) {
4668 rights = *cap_rights(fdp, i);
4669 #else /* !CAPABILITIES */
4670 rights = cap_no_rights;
4673 * Create sysctl entry. It is OK to drop the filedesc
4674 * lock inside of export_file_to_sb() as we will
4675 * re-validate and re-evaluate its properties when the
4678 error = export_file_to_sb(fp, i, &rights, efbuf);
4679 if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4683 FILEDESC_SUNLOCK(fdp);
4689 free(efbuf, M_TEMP);
4693 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
4696 * Get per-process file descriptors for use by procstat(1), et al.
4699 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4705 int error, error2, *name;
4713 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4714 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4715 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4720 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4721 error = kern_proc_filedesc_out(p, &sb, maxlen,
4722 KERN_FILEDESC_PACK_KINFO);
4723 error2 = sbuf_finish(&sb);
4725 return (error != 0 ? error : error2);
4728 #ifdef COMPAT_FREEBSD7
4729 #ifdef KINFO_OFILE_SIZE
4730 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4734 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4737 okif->kf_structsize = sizeof(*okif);
4738 okif->kf_type = kif->kf_type;
4739 okif->kf_fd = kif->kf_fd;
4740 okif->kf_ref_count = kif->kf_ref_count;
4741 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4742 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4743 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4744 okif->kf_offset = kif->kf_offset;
4745 if (kif->kf_type == KF_TYPE_VNODE)
4746 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4748 okif->kf_vnode_type = KF_VTYPE_VNON;
4749 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4750 if (kif->kf_type == KF_TYPE_SOCKET) {
4751 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4752 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4753 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4754 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4755 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4757 okif->kf_sa_local.ss_family = AF_UNSPEC;
4758 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4763 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4764 struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4769 PWDDESC_XUNLOCK(pdp);
4770 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4771 kinfo_to_okinfo(kif, okif);
4772 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4778 * Get per-process file descriptors for use by procstat(1), et al.
4781 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4783 struct kinfo_ofile *okif;
4784 struct kinfo_file *kif;
4785 struct filedesc *fdp;
4786 struct pwddesc *pdp;
4789 int error, i, *name;
4798 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4805 if (fdp == NULL || pdp == NULL) {
4810 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4811 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4813 pwd = pwd_hold_pwddesc(pdp);
4815 if (pwd->pwd_cdir != NULL)
4816 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4818 if (pwd->pwd_rdir != NULL)
4819 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4821 if (pwd->pwd_jdir != NULL)
4822 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4825 PWDDESC_XUNLOCK(pdp);
4828 FILEDESC_SLOCK(fdp);
4829 if (refcount_load(&fdp->fd_refcnt) == 0)
4831 FILEDESC_FOREACH_FP(fdp, i, fp) {
4832 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4833 KERN_FILEDESC_PACK_KINFO);
4834 FILEDESC_SUNLOCK(fdp);
4835 kinfo_to_okinfo(kif, okif);
4836 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4837 FILEDESC_SLOCK(fdp);
4838 if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4842 FILEDESC_SUNLOCK(fdp);
4850 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4851 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4852 "Process ofiledesc entries");
4853 #endif /* COMPAT_FREEBSD7 */
4856 vntype_to_kinfo(int vtype)
4861 } vtypes_table[] = {
4862 { VBAD, KF_VTYPE_VBAD },
4863 { VBLK, KF_VTYPE_VBLK },
4864 { VCHR, KF_VTYPE_VCHR },
4865 { VDIR, KF_VTYPE_VDIR },
4866 { VFIFO, KF_VTYPE_VFIFO },
4867 { VLNK, KF_VTYPE_VLNK },
4868 { VNON, KF_VTYPE_VNON },
4869 { VREG, KF_VTYPE_VREG },
4870 { VSOCK, KF_VTYPE_VSOCK }
4875 * Perform vtype translation.
4877 for (i = 0; i < nitems(vtypes_table); i++)
4878 if (vtypes_table[i].vtype == vtype)
4879 return (vtypes_table[i].kf_vtype);
4881 return (KF_VTYPE_UNKNOWN);
4884 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4885 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4886 "Process filedesc entries");
4889 * Store a process current working directory information to sbuf.
4891 * Takes a locked proc as argument, and returns with the proc unlocked.
4894 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4896 struct pwddesc *pdp;
4898 struct export_fd_buf *efbuf;
4902 PROC_LOCK_ASSERT(p, MA_OWNED);
4909 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4913 efbuf->remainder = maxlen;
4917 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4918 cdir = pwd->pwd_cdir;
4923 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4925 PWDDESC_XUNLOCK(pdp);
4927 free(efbuf, M_TEMP);
4932 * Get per-process current working directory.
4935 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4941 int error, error2, *name;
4949 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4950 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4951 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4956 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4957 error = kern_proc_cwd_out(p, &sb, maxlen);
4958 error2 = sbuf_finish(&sb);
4960 return (error != 0 ? error : error2);
4963 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4964 sysctl_kern_proc_cwd, "Process current working directory");
4968 * For the purposes of debugging, generate a human-readable string for the
4972 file_type_to_name(short type)
5000 case DTYPE_PROCDESC:
5012 * For the purposes of debugging, identify a process (if any, perhaps one of
5013 * many) that references the passed file in its file descriptor array. Return
5016 static struct proc *
5017 file_to_first_proc(struct file *fp)
5019 struct filedesc *fdp;
5023 FOREACH_PROC_IN_SYSTEM(p) {
5024 if (p->p_state == PRS_NEW)
5029 for (n = 0; n < fdp->fd_nfiles; n++) {
5030 if (fp == fdp->fd_ofiles[n].fde_file)
5038 db_print_file(struct file *fp, int header)
5040 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
5044 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
5045 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
5046 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
5048 p = file_to_first_proc(fp);
5049 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
5050 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
5051 fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
5052 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
5057 DB_SHOW_COMMAND(file, db_show_file)
5062 db_printf("usage: show file <addr>\n");
5065 fp = (struct file *)addr;
5066 db_print_file(fp, 1);
5069 DB_SHOW_COMMAND_FLAGS(files, db_show_files, DB_CMD_MEMSAFE)
5071 struct filedesc *fdp;
5078 FOREACH_PROC_IN_SYSTEM(p) {
5079 if (p->p_state == PRS_NEW)
5081 if ((fdp = p->p_fd) == NULL)
5083 for (n = 0; n < fdp->fd_nfiles; ++n) {
5084 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
5086 db_print_file(fp, header);
5093 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
5094 CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5095 &maxfilesperproc, 0, "Maximum files allowed open per process");
5097 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5098 &maxfiles, 0, "Maximum number of files");
5100 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
5101 &openfiles, 0, "System-wide number of open files");
5105 filelistinit(void *dummy)
5108 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
5109 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
5110 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
5111 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5112 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
5113 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
5115 * XXXMJG this is a temporary hack due to boot ordering issues against
5118 vfs_smr = uma_zone_get_smr(pwd_zone);
5119 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
5121 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
5123 /*-------------------------------------------------------------------*/
5126 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
5127 int flags, struct thread *td)
5134 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5142 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
5150 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
5158 badfo_kqfilter(struct file *fp, struct knote *kn)
5165 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
5172 badfo_close(struct file *fp, struct thread *td)
5179 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5187 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5195 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5196 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5204 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
5210 struct fileops badfileops = {
5211 .fo_read = badfo_readwrite,
5212 .fo_write = badfo_readwrite,
5213 .fo_truncate = badfo_truncate,
5214 .fo_ioctl = badfo_ioctl,
5215 .fo_poll = badfo_poll,
5216 .fo_kqfilter = badfo_kqfilter,
5217 .fo_stat = badfo_stat,
5218 .fo_close = badfo_close,
5219 .fo_chmod = badfo_chmod,
5220 .fo_chown = badfo_chown,
5221 .fo_sendfile = badfo_sendfile,
5222 .fo_fill_kinfo = badfo_fill_kinfo,
5226 path_poll(struct file *fp, int events, struct ucred *active_cred,
5233 path_close(struct file *fp, struct thread *td)
5235 MPASS(fp->f_type == DTYPE_VNODE);
5236 fp->f_ops = &badfileops;
5241 struct fileops path_fileops = {
5242 .fo_read = badfo_readwrite,
5243 .fo_write = badfo_readwrite,
5244 .fo_truncate = badfo_truncate,
5245 .fo_ioctl = badfo_ioctl,
5246 .fo_poll = path_poll,
5247 .fo_kqfilter = vn_kqfilter_opath,
5248 .fo_stat = vn_statfile,
5249 .fo_close = path_close,
5250 .fo_chmod = badfo_chmod,
5251 .fo_chown = badfo_chown,
5252 .fo_sendfile = badfo_sendfile,
5253 .fo_fill_kinfo = vn_fill_kinfo,
5254 .fo_flags = DFLAG_PASSABLE,
5258 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
5259 int flags, struct thread *td)
5262 return (EOPNOTSUPP);
5266 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5274 invfo_ioctl(struct file *fp, u_long com, void *data,
5275 struct ucred *active_cred, struct thread *td)
5282 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
5286 return (poll_no_poll(events));
5290 invfo_kqfilter(struct file *fp, struct knote *kn)
5297 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5305 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5313 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5314 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5321 /*-------------------------------------------------------------------*/
5324 * File Descriptor pseudo-device driver (/dev/fd/).
5326 * Opening minor device N dup()s the file (if any) connected to file
5327 * descriptor N belonging to the calling process. Note that this driver
5328 * consists of only the ``open()'' routine, because all subsequent
5329 * references to this file will be direct to the other driver.
5331 * XXX: we could give this one a cloning event handler if necessary.
5336 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5340 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5341 * the file descriptor being sought for duplication. The error
5342 * return ensures that the vnode for this device will be released
5343 * by vn_open. Open will detect this special error and take the
5344 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5345 * will simply report the error.
5347 td->td_dupfd = dev2unit(dev);
5351 static struct cdevsw fildesc_cdevsw = {
5352 .d_version = D_VERSION,
5358 fildesc_drvinit(void *unused)
5362 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5363 UID_ROOT, GID_WHEEL, 0666, "fd/0");
5364 make_dev_alias(dev, "stdin");
5365 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5366 UID_ROOT, GID_WHEEL, 0666, "fd/1");
5367 make_dev_alias(dev, "stdout");
5368 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5369 UID_ROOT, GID_WHEEL, 0666, "fd/2");
5370 make_dev_alias(dev, "stderr");
5373 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);