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 filedesc *fdp, 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)
157 * SLIST entry used to keep track of ofiles which must be reclaimed when
161 struct fdescenttbl *ft_table;
162 SLIST_ENTRY(freetable) ft_next;
166 * Initial allocation: a filedesc structure + the head of SLIST used to
167 * keep track of old ofiles + enough space for NDFILE descriptors.
170 struct fdescenttbl0 {
172 struct filedescent fdt_ofiles[NDFILE];
176 struct filedesc fd_fd;
177 SLIST_HEAD(, freetable) fd_free;
178 struct fdescenttbl0 fd_dfiles;
179 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
183 * Descriptor management.
185 static int __exclusive_cache_line openfiles; /* actual number of open files */
186 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
187 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
190 * If low >= size, just return low. Otherwise find the first zero bit in the
191 * given bitmap, starting at low and not exceeding size - 1. Return size if
195 fd_first_free(struct filedesc *fdp, int low, int size)
197 NDSLOTTYPE *map = fdp->fd_map;
205 if (low % NDENTRIES) {
206 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
207 if ((mask &= ~map[off]) != 0UL)
208 return (off * NDENTRIES + ffsl(mask) - 1);
211 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
212 if (map[off] != ~0UL)
213 return (off * NDENTRIES + ffsl(~map[off]) - 1);
218 * Find the last used fd.
220 * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
221 * Otherwise use fdlastfile.
224 fdlastfile_single(struct filedesc *fdp)
226 NDSLOTTYPE *map = fdp->fd_map;
229 off = NDSLOT(fdp->fd_nfiles - 1);
230 for (minoff = NDSLOT(0); off >= minoff; --off)
232 return (off * NDENTRIES + flsl(map[off]) - 1);
237 fdlastfile(struct filedesc *fdp)
240 FILEDESC_LOCK_ASSERT(fdp);
241 return (fdlastfile_single(fdp));
245 fdisused(struct filedesc *fdp, int fd)
248 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
249 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
251 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
255 * Mark a file descriptor as used.
258 fdused_init(struct filedesc *fdp, int fd)
261 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
263 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
267 fdused(struct filedesc *fdp, int fd)
270 FILEDESC_XLOCK_ASSERT(fdp);
272 fdused_init(fdp, fd);
273 if (fd == fdp->fd_freefile)
278 * Mark a file descriptor as unused.
281 fdunused(struct filedesc *fdp, int fd)
284 FILEDESC_XLOCK_ASSERT(fdp);
286 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
287 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
288 ("fd=%d is still in use", fd));
290 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
291 if (fd < fdp->fd_freefile)
292 fdp->fd_freefile = fd;
296 * Free a file descriptor.
298 * Avoid some work if fdp is about to be destroyed.
301 fdefree_last(struct filedescent *fde)
304 filecaps_free(&fde->fde_caps);
308 fdfree(struct filedesc *fdp, int fd)
310 struct filedescent *fde;
312 FILEDESC_XLOCK_ASSERT(fdp);
313 fde = &fdp->fd_ofiles[fd];
315 seqc_write_begin(&fde->fde_seqc);
317 fde->fde_file = NULL;
319 seqc_write_end(&fde->fde_seqc);
326 * System calls on descriptors.
328 #ifndef _SYS_SYSPROTO_H_
329 struct getdtablesize_args {
335 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
341 td->td_retval[0] = getmaxfd(td);
343 PROC_LOCK(td->td_proc);
344 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
345 PROC_UNLOCK(td->td_proc);
346 if (lim < td->td_retval[0])
347 td->td_retval[0] = lim;
353 * Duplicate a file descriptor to a particular value.
355 * Note: keep in mind that a potential race condition exists when closing
356 * descriptors from a shared descriptor table (via rfork).
358 #ifndef _SYS_SYSPROTO_H_
366 sys_dup2(struct thread *td, struct dup2_args *uap)
369 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
373 * Duplicate a file descriptor.
375 #ifndef _SYS_SYSPROTO_H_
382 sys_dup(struct thread *td, struct dup_args *uap)
385 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
389 * The file control system call.
391 #ifndef _SYS_SYSPROTO_H_
400 sys_fcntl(struct thread *td, struct fcntl_args *uap)
403 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
407 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
421 * Convert old flock structure to new.
423 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
424 fl.l_start = ofl.l_start;
425 fl.l_len = ofl.l_len;
426 fl.l_pid = ofl.l_pid;
427 fl.l_type = ofl.l_type;
428 fl.l_whence = ofl.l_whence;
442 arg1 = (intptr_t)&fl;
448 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
449 arg1 = (intptr_t)&fl;
457 error = kern_fcntl(td, fd, newcmd, arg1);
460 if (cmd == F_OGETLK) {
461 ofl.l_start = fl.l_start;
462 ofl.l_len = fl.l_len;
463 ofl.l_pid = fl.l_pid;
464 ofl.l_type = fl.l_type;
465 ofl.l_whence = fl.l_whence;
466 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
467 } else if (cmd == F_GETLK) {
468 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
474 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
476 struct filedesc *fdp;
478 struct file *fp, *fp2;
479 struct filedescent *fde;
483 struct kinfo_file *kif;
484 int error, flg, kif_sz, seals, tmp, got_set, got_cleared;
498 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
501 case F_DUPFD_CLOEXEC:
503 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
508 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
511 case F_DUP2FD_CLOEXEC:
513 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
519 fde = fdeget_locked(fdp, fd);
522 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
525 FILEDESC_SUNLOCK(fdp);
531 fde = fdeget_locked(fdp, fd);
533 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
534 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
537 FILEDESC_XUNLOCK(fdp);
541 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
544 td->td_retval[0] = OFLAGS(fp->f_flag);
549 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
552 if (fp->f_ops == &path_fileops) {
558 tmp = flg = fp->f_flag;
560 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
561 } while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
562 got_set = tmp & ~flg;
563 got_cleared = flg & ~tmp;
564 tmp = fp->f_flag & FNONBLOCK;
565 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
568 tmp = fp->f_flag & FASYNC;
569 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
574 atomic_clear_int(&fp->f_flag, FNONBLOCK);
576 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
579 tmp = flg = fp->f_flag;
583 } while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
588 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
591 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
593 td->td_retval[0] = tmp;
598 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
602 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
607 error = priv_check(td, PRIV_NFS_LOCKD);
615 /* FALLTHROUGH F_SETLK */
619 flp = (struct flock *)arg;
620 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
625 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
628 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
634 if (flp->l_whence == SEEK_CUR) {
635 foffset = foffset_get(fp);
638 foffset > OFF_MAX - flp->l_start)) {
643 flp->l_start += foffset;
647 switch (flp->l_type) {
649 if ((fp->f_flag & FREAD) == 0) {
653 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
654 PROC_LOCK(p->p_leader);
655 p->p_leader->p_flag |= P_ADVLOCK;
656 PROC_UNLOCK(p->p_leader);
658 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
662 if ((fp->f_flag & FWRITE) == 0) {
666 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
667 PROC_LOCK(p->p_leader);
668 p->p_leader->p_flag |= P_ADVLOCK;
669 PROC_UNLOCK(p->p_leader);
671 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
675 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
679 if (flg != F_REMOTE) {
683 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
684 F_UNLCKSYS, flp, flg);
690 if (error != 0 || flp->l_type == F_UNLCK ||
691 flp->l_type == F_UNLCKSYS) {
697 * Check for a race with close.
699 * The vnode is now advisory locked (or unlocked, but this case
700 * is not really important) as the caller requested.
701 * We had to drop the filedesc lock, so we need to recheck if
702 * the descriptor is still valid, because if it was closed
703 * in the meantime we need to remove advisory lock from the
704 * vnode - close on any descriptor leading to an advisory
705 * locked vnode, removes that lock.
706 * We will return 0 on purpose in that case, as the result of
707 * successful advisory lock might have been externally visible
708 * already. This is fine - effectively we pretend to the caller
709 * that the closing thread was a bit slower and that the
710 * advisory lock succeeded before the close.
712 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
718 flp->l_whence = SEEK_SET;
721 flp->l_type = F_UNLCK;
722 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
723 F_UNLCK, flp, F_POSIX);
730 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
733 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
738 flp = (struct flock *)arg;
739 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
740 flp->l_type != F_UNLCK) {
745 if (flp->l_whence == SEEK_CUR) {
746 foffset = foffset_get(fp);
747 if ((flp->l_start > 0 &&
748 foffset > OFF_MAX - flp->l_start) ||
750 foffset < OFF_MIN - flp->l_start)) {
755 flp->l_start += foffset;
758 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
764 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
767 error = fo_add_seals(fp, arg);
772 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
775 if (fo_get_seals(fp, &seals) == 0)
776 td->td_retval[0] = seals;
783 arg = arg ? 128 * 1024: 0;
786 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
789 if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
795 if (vp->v_type != VREG) {
802 * Exclusive lock synchronizes against f_seqcount reads and
803 * writes in sequential_heuristic().
805 error = vn_lock(vp, LK_EXCLUSIVE);
811 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
812 arg = MIN(arg, INT_MAX - bsize + 1);
813 fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
814 (arg + bsize - 1) / bsize);
815 atomic_set_int(&fp->f_flag, FRDAHEAD);
817 atomic_clear_int(&fp->f_flag, FRDAHEAD);
825 * Check if the vnode is part of a union stack (either the
826 * "union" flag from mount(2) or unionfs).
828 * Prior to introduction of this op libc's readdir would call
829 * fstatfs(2), in effect unnecessarily copying kilobytes of
830 * data just to check fs name and a mount flag.
832 * Fixing the code to handle everything in the kernel instead
833 * is a non-trivial endeavor and has low priority, thus this
834 * horrible kludge facilitates the current behavior in a much
835 * cheaper manner until someone(tm) sorts this out.
837 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
840 if (fp->f_type != DTYPE_VNODE) {
847 * Since we don't prevent dooming the vnode even non-null mp
848 * found can become immediately stale. This is tolerable since
849 * mount points are type-stable (providing safe memory access)
850 * and any vfs op on this vnode going forward will return an
851 * error (meaning return value in this case is meaningless).
853 mp = atomic_load_ptr(&vp->v_mount);
854 if (__predict_false(mp == NULL)) {
859 td->td_retval[0] = 0;
860 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
861 mp->mnt_flag & MNT_UNION)
862 td->td_retval[0] = 1;
867 #ifdef CAPABILITY_MODE
868 if (IN_CAPABILITY_MODE(td)) {
873 error = copyin((void *)arg, &kif_sz, sizeof(kif_sz));
876 if (kif_sz != sizeof(*kif)) {
880 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK | M_ZERO);
882 error = fget_cap_locked(fdp, fd, &cap_fcntl_rights, &fp, NULL);
883 if (error == 0 && fhold(fp)) {
884 export_file_to_kinfo(fp, fd, NULL, kif, fdp, 0);
885 FILEDESC_SUNLOCK(fdp);
887 if ((kif->kf_status & KF_ATTR_VALID) != 0) {
888 kif->kf_structsize = sizeof(*kif);
889 error = copyout(kif, (void *)arg, sizeof(*kif));
894 FILEDESC_SUNLOCK(fdp);
909 getmaxfd(struct thread *td)
912 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
916 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
919 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
921 struct filedesc *fdp;
922 struct filedescent *oldfde, *newfde;
924 struct file *delfp, *oldfp;
925 u_long *oioctls, *nioctls;
932 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
933 MPASS(mode < FDDUP_LASTMODE);
936 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
939 * Verify we have a valid descriptor to dup from and possibly to
940 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
941 * return EINVAL when the new descriptor is out of bounds.
946 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
947 maxfd = getmaxfd(td);
949 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
953 if (fget_locked(fdp, old) == NULL)
955 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
956 td->td_retval[0] = new;
957 if (flags & FDDUP_FLAG_CLOEXEC)
958 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
963 oldfde = &fdp->fd_ofiles[old];
964 oldfp = oldfde->fde_file;
969 * If the caller specified a file descriptor, make sure the file
970 * table is large enough to hold it, and grab it. Otherwise, just
971 * allocate a new descriptor the usual way.
976 if ((error = fdalloc(td, new, &new)) != 0) {
981 case FDDUP_MUSTREPLACE:
982 /* Target file descriptor must exist. */
983 if (fget_locked(fdp, new) == NULL) {
989 if (new >= fdp->fd_nfiles) {
991 * The resource limits are here instead of e.g.
992 * fdalloc(), because the file descriptor table may be
993 * shared between processes, so we can't really use
994 * racct_add()/racct_sub(). Instead of counting the
995 * number of actually allocated descriptors, just put
996 * the limit on the size of the file descriptor table.
999 if (RACCT_ENABLED()) {
1000 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
1008 fdgrowtable_exp(fdp, new + 1);
1010 if (!fdisused(fdp, new))
1014 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
1017 KASSERT(old != new, ("new fd is same as old"));
1019 /* Refetch oldfde because the table may have grown and old one freed. */
1020 oldfde = &fdp->fd_ofiles[old];
1021 KASSERT(oldfp == oldfde->fde_file,
1022 ("fdt_ofiles shift from growth observed at fd %d",
1025 newfde = &fdp->fd_ofiles[new];
1026 delfp = newfde->fde_file;
1028 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
1031 * Duplicate the source descriptor.
1034 seqc_write_begin(&newfde->fde_seqc);
1036 oioctls = filecaps_free_prep(&newfde->fde_caps);
1037 memcpy(newfde, oldfde, fde_change_size);
1038 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
1040 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
1041 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
1043 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
1045 seqc_write_end(&newfde->fde_seqc);
1047 td->td_retval[0] = new;
1051 if (delfp != NULL) {
1052 (void) closefp(fdp, new, delfp, td, true, false);
1053 FILEDESC_UNLOCK_ASSERT(fdp);
1056 FILEDESC_XUNLOCK(fdp);
1059 filecaps_free_finish(oioctls);
1064 sigiofree(struct sigio *sigio)
1066 crfree(sigio->sio_ucred);
1067 free(sigio, M_SIGIO);
1070 static struct sigio *
1071 funsetown_locked(struct sigio *sigio)
1076 SIGIO_ASSERT_LOCKED();
1080 *sigio->sio_myref = NULL;
1081 if (sigio->sio_pgid < 0) {
1082 pg = sigio->sio_pgrp;
1084 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1087 p = sigio->sio_proc;
1089 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1096 * If sigio is on the list associated with a process or process group,
1097 * disable signalling from the device, remove sigio from the list and
1101 funsetown(struct sigio **sigiop)
1103 struct sigio *sigio;
1105 /* Racy check, consumers must provide synchronization. */
1106 if (*sigiop == NULL)
1110 sigio = funsetown_locked(*sigiop);
1117 * Free a list of sigio structures. The caller must ensure that new sigio
1118 * structures cannot be added after this point. For process groups this is
1119 * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1123 funsetownlst(struct sigiolst *sigiolst)
1127 struct sigio *sigio, *tmp;
1130 sigio = SLIST_FIRST(sigiolst);
1138 sigio = SLIST_FIRST(sigiolst);
1139 if (sigio == NULL) {
1145 * Every entry of the list should belong to a single proc or pgrp.
1147 if (sigio->sio_pgid < 0) {
1148 pg = sigio->sio_pgrp;
1149 sx_assert(&proctree_lock, SX_XLOCKED);
1151 } else /* if (sigio->sio_pgid > 0) */ {
1152 p = sigio->sio_proc;
1154 KASSERT((p->p_flag & P_WEXIT) != 0,
1155 ("%s: process %p is not exiting", __func__, p));
1158 SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1159 *sigio->sio_myref = NULL;
1161 KASSERT(sigio->sio_pgid < 0,
1162 ("Proc sigio in pgrp sigio list"));
1163 KASSERT(sigio->sio_pgrp == pg,
1164 ("Bogus pgrp in sigio list"));
1165 } else /* if (p != NULL) */ {
1166 KASSERT(sigio->sio_pgid > 0,
1167 ("Pgrp sigio in proc sigio list"));
1168 KASSERT(sigio->sio_proc == p,
1169 ("Bogus proc in sigio list"));
1179 SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1184 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1186 * After permission checking, add a sigio structure to the sigio list for
1187 * the process or process group.
1190 fsetown(pid_t pgid, struct sigio **sigiop)
1194 struct sigio *osigio, *sigio;
1202 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1203 sigio->sio_pgid = pgid;
1204 sigio->sio_ucred = crhold(curthread->td_ucred);
1205 sigio->sio_myref = sigiop;
1209 ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1211 osigio = funsetown_locked(*sigiop);
1215 if ((proc->p_flag & P_WEXIT) != 0) {
1217 } else if (proc->p_session !=
1218 curthread->td_proc->p_session) {
1220 * Policy - Don't allow a process to FSETOWN a
1221 * process in another session.
1223 * Remove this test to allow maximum flexibility
1224 * or restrict FSETOWN to the current process or
1225 * process group for maximum safety.
1229 sigio->sio_proc = proc;
1230 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1235 } else /* if (pgid < 0) */ {
1236 sx_slock(&proctree_lock);
1238 osigio = funsetown_locked(*sigiop);
1239 pgrp = pgfind(-pgid);
1243 if (pgrp->pg_session != curthread->td_proc->p_session) {
1245 * Policy - Don't allow a process to FSETOWN a
1246 * process in another session.
1248 * Remove this test to allow maximum flexibility
1249 * or restrict FSETOWN to the current process or
1250 * process group for maximum safety.
1254 sigio->sio_pgrp = pgrp;
1255 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1260 sx_sunlock(&proctree_lock);
1271 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1274 fgetown(struct sigio **sigiop)
1279 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1285 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1290 FILEDESC_XLOCK_ASSERT(fdp);
1293 * We now hold the fp reference that used to be owned by the
1294 * descriptor array. We have to unlock the FILEDESC *AFTER*
1295 * knote_fdclose to prevent a race of the fd getting opened, a knote
1296 * added, and deleteing a knote for the new fd.
1298 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1299 knote_fdclose(td, fd);
1302 * We need to notify mqueue if the object is of type mqueue.
1304 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1305 mq_fdclose(td, fd, fp);
1306 FILEDESC_XUNLOCK(fdp);
1309 if (AUDITING_TD(td) && audit)
1310 audit_sysclose(td, fd, fp);
1312 error = closef(fp, td);
1315 * All paths leading up to closefp() will have already removed or
1316 * replaced the fd in the filedesc table, so a restart would not
1317 * operate on the same file.
1319 if (error == ERESTART)
1326 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1327 bool holdleaders, bool audit)
1331 FILEDESC_XLOCK_ASSERT(fdp);
1334 if (td->td_proc->p_fdtol != NULL) {
1336 * Ask fdfree() to sleep to ensure that all relevant
1337 * process leaders can be traversed in closef().
1339 fdp->fd_holdleaderscount++;
1341 holdleaders = false;
1345 error = closefp_impl(fdp, fd, fp, td, audit);
1347 FILEDESC_XLOCK(fdp);
1348 fdp->fd_holdleaderscount--;
1349 if (fdp->fd_holdleaderscount == 0 &&
1350 fdp->fd_holdleaderswakeup != 0) {
1351 fdp->fd_holdleaderswakeup = 0;
1352 wakeup(&fdp->fd_holdleaderscount);
1354 FILEDESC_XUNLOCK(fdp);
1360 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1361 bool holdleaders, bool audit)
1364 FILEDESC_XLOCK_ASSERT(fdp);
1366 if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1367 return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1369 return (closefp_impl(fdp, fd, fp, td, audit));
1374 * Close a file descriptor.
1376 #ifndef _SYS_SYSPROTO_H_
1383 sys_close(struct thread *td, struct close_args *uap)
1386 return (kern_close(td, uap->fd));
1390 kern_close(struct thread *td, int fd)
1392 struct filedesc *fdp;
1395 fdp = td->td_proc->p_fd;
1397 FILEDESC_XLOCK(fdp);
1398 if ((fp = fget_locked(fdp, fd)) == NULL) {
1399 FILEDESC_XUNLOCK(fdp);
1404 /* closefp() drops the FILEDESC lock for us. */
1405 return (closefp(fdp, fd, fp, td, true, true));
1409 close_range_cloexec(struct thread *td, u_int lowfd, u_int highfd)
1411 struct filedesc *fdp;
1412 struct fdescenttbl *fdt;
1413 struct filedescent *fde;
1416 fdp = td->td_proc->p_fd;
1417 FILEDESC_XLOCK(fdp);
1418 fdt = atomic_load_ptr(&fdp->fd_files);
1419 highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1421 if (__predict_false(fd > highfd)) {
1424 for (; fd <= highfd; fd++) {
1425 fde = &fdt->fdt_ofiles[fd];
1426 if (fde->fde_file != NULL)
1427 fde->fde_flags |= UF_EXCLOSE;
1430 FILEDESC_XUNLOCK(fdp);
1435 close_range_impl(struct thread *td, u_int lowfd, u_int highfd)
1437 struct filedesc *fdp;
1438 const struct fdescenttbl *fdt;
1442 fdp = td->td_proc->p_fd;
1443 FILEDESC_XLOCK(fdp);
1444 fdt = atomic_load_ptr(&fdp->fd_files);
1445 highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1447 if (__predict_false(fd > highfd)) {
1451 fp = fdt->fdt_ofiles[fd].fde_file;
1457 (void) closefp(fdp, fd, fp, td, true, true);
1460 FILEDESC_XLOCK(fdp);
1461 fdt = atomic_load_ptr(&fdp->fd_files);
1466 FILEDESC_XUNLOCK(fdp);
1472 kern_close_range(struct thread *td, int flags, u_int lowfd, u_int highfd)
1476 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1477 * open should not be a usage error. From a close_range() perspective,
1478 * close_range(3, ~0U, 0) in the same scenario should also likely not
1479 * be a usage error as all fd above 3 are in-fact already closed.
1481 if (highfd < lowfd) {
1485 if ((flags & CLOSE_RANGE_CLOEXEC) != 0)
1486 return (close_range_cloexec(td, lowfd, highfd));
1488 return (close_range_impl(td, lowfd, highfd));
1491 #ifndef _SYS_SYSPROTO_H_
1492 struct close_range_args {
1499 sys_close_range(struct thread *td, struct close_range_args *uap)
1502 AUDIT_ARG_FD(uap->lowfd);
1503 AUDIT_ARG_CMD(uap->highfd);
1504 AUDIT_ARG_FFLAGS(uap->flags);
1506 if ((uap->flags & ~(CLOSE_RANGE_CLOEXEC)) != 0)
1508 return (kern_close_range(td, uap->flags, uap->lowfd, uap->highfd));
1511 #ifdef COMPAT_FREEBSD12
1513 * Close open file descriptors.
1515 #ifndef _SYS_SYSPROTO_H_
1516 struct freebsd12_closefrom_args {
1522 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1526 AUDIT_ARG_FD(uap->lowfd);
1529 * Treat negative starting file descriptor values identical to
1530 * closefrom(0) which closes all files.
1532 lowfd = MAX(0, uap->lowfd);
1533 return (kern_close_range(td, 0, lowfd, ~0U));
1535 #endif /* COMPAT_FREEBSD12 */
1537 #if defined(COMPAT_43)
1539 * Return status information about a file descriptor.
1541 #ifndef _SYS_SYSPROTO_H_
1542 struct ofstat_args {
1549 ofstat(struct thread *td, struct ofstat_args *uap)
1555 error = kern_fstat(td, uap->fd, &ub);
1558 error = copyout(&oub, uap->sb, sizeof(oub));
1562 #endif /* COMPAT_43 */
1564 #if defined(COMPAT_FREEBSD11)
1566 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1569 struct freebsd11_stat osb;
1572 error = kern_fstat(td, uap->fd, &sb);
1575 error = freebsd11_cvtstat(&sb, &osb);
1577 error = copyout(&osb, uap->sb, sizeof(osb));
1580 #endif /* COMPAT_FREEBSD11 */
1583 * Return status information about a file descriptor.
1585 #ifndef _SYS_SYSPROTO_H_
1593 sys_fstat(struct thread *td, struct fstat_args *uap)
1598 error = kern_fstat(td, uap->fd, &ub);
1600 error = copyout(&ub, uap->sb, sizeof(ub));
1605 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1612 error = fget(td, fd, &cap_fstat_rights, &fp);
1613 if (__predict_false(error != 0))
1616 AUDIT_ARG_FILE(td->td_proc, fp);
1618 error = fo_stat(fp, sbp, td->td_ucred, td);
1620 #ifdef __STAT_TIME_T_EXT
1621 sbp->st_atim_ext = 0;
1622 sbp->st_mtim_ext = 0;
1623 sbp->st_ctim_ext = 0;
1624 sbp->st_btim_ext = 0;
1627 if (KTRPOINT(td, KTR_STRUCT))
1628 ktrstat_error(sbp, error);
1633 #if defined(COMPAT_FREEBSD11)
1635 * Return status information about a file descriptor.
1637 #ifndef _SYS_SYSPROTO_H_
1638 struct freebsd11_nfstat_args {
1645 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1651 error = kern_fstat(td, uap->fd, &ub);
1653 freebsd11_cvtnstat(&ub, &nub);
1654 error = copyout(&nub, uap->sb, sizeof(nub));
1658 #endif /* COMPAT_FREEBSD11 */
1661 * Return pathconf information about a file descriptor.
1663 #ifndef _SYS_SYSPROTO_H_
1664 struct fpathconf_args {
1671 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1676 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1678 td->td_retval[0] = value;
1683 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1689 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1693 if (name == _PC_ASYNC_IO) {
1694 *valuep = _POSIX_ASYNCHRONOUS_IO;
1699 vn_lock(vp, LK_SHARED | LK_RETRY);
1700 error = VOP_PATHCONF(vp, name, valuep);
1702 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1703 if (name != _PC_PIPE_BUF) {
1718 * Copy filecaps structure allocating memory for ioctls array if needed.
1720 * The last parameter indicates whether the fdtable is locked. If it is not and
1721 * ioctls are encountered, copying fails and the caller must lock the table.
1723 * Note that if the table was not locked, the caller has to check the relevant
1724 * sequence counter to determine whether the operation was successful.
1727 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1731 if (src->fc_ioctls != NULL && !locked)
1733 memcpy(dst, src, sizeof(*src));
1734 if (src->fc_ioctls == NULL)
1737 KASSERT(src->fc_nioctls > 0,
1738 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1740 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1741 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1742 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1747 filecaps_copy_prep(const struct filecaps *src)
1752 if (__predict_true(src->fc_ioctls == NULL))
1755 KASSERT(src->fc_nioctls > 0,
1756 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1758 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1759 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1764 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1770 if (__predict_true(src->fc_ioctls == NULL)) {
1771 MPASS(ioctls == NULL);
1775 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1776 dst->fc_ioctls = ioctls;
1777 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1781 * Move filecaps structure to the new place and clear the old place.
1784 filecaps_move(struct filecaps *src, struct filecaps *dst)
1788 bzero(src, sizeof(*src));
1792 * Fill the given filecaps structure with full rights.
1795 filecaps_fill(struct filecaps *fcaps)
1798 CAP_ALL(&fcaps->fc_rights);
1799 fcaps->fc_ioctls = NULL;
1800 fcaps->fc_nioctls = -1;
1801 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1805 * Free memory allocated within filecaps structure.
1808 filecaps_free_ioctl(struct filecaps *fcaps)
1811 free(fcaps->fc_ioctls, M_FILECAPS);
1812 fcaps->fc_ioctls = NULL;
1816 filecaps_free(struct filecaps *fcaps)
1819 filecaps_free_ioctl(fcaps);
1820 bzero(fcaps, sizeof(*fcaps));
1824 filecaps_free_prep(struct filecaps *fcaps)
1828 ioctls = fcaps->fc_ioctls;
1829 bzero(fcaps, sizeof(*fcaps));
1834 filecaps_free_finish(u_long *ioctls)
1837 free(ioctls, M_FILECAPS);
1841 * Validate the given filecaps structure.
1844 filecaps_validate(const struct filecaps *fcaps, const char *func)
1847 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1848 ("%s: invalid rights", func));
1849 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1850 ("%s: invalid fcntls", func));
1851 KASSERT(fcaps->fc_fcntls == 0 ||
1852 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1853 ("%s: fcntls without CAP_FCNTL", func));
1855 * open calls without WANTIOCTLCAPS free caps but leave the counter
1858 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1859 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1860 ("%s: invalid ioctls", func));
1862 KASSERT(fcaps->fc_nioctls == 0 ||
1863 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1864 ("%s: ioctls without CAP_IOCTL", func));
1868 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1872 FILEDESC_XLOCK_ASSERT(fdp);
1874 nfd1 = fdp->fd_nfiles * 2;
1877 fdgrowtable(fdp, nfd1);
1881 * Grow the file table to accommodate (at least) nfd descriptors.
1884 fdgrowtable(struct filedesc *fdp, int nfd)
1886 struct filedesc0 *fdp0;
1887 struct freetable *ft;
1888 struct fdescenttbl *ntable;
1889 struct fdescenttbl *otable;
1890 int nnfiles, onfiles;
1891 NDSLOTTYPE *nmap, *omap;
1893 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1895 /* save old values */
1896 onfiles = fdp->fd_nfiles;
1897 otable = fdp->fd_files;
1900 /* compute the size of the new table */
1901 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1902 if (nnfiles <= onfiles)
1903 /* the table is already large enough */
1907 * Allocate a new table. We need enough space for the number of
1908 * entries, file entries themselves and the struct freetable we will use
1909 * when we decommission the table and place it on the freelist.
1910 * We place the struct freetable in the middle so we don't have
1911 * to worry about padding.
1913 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1914 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1915 sizeof(struct freetable),
1916 M_FILEDESC, M_ZERO | M_WAITOK);
1917 /* copy the old data */
1918 ntable->fdt_nfiles = nnfiles;
1919 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1920 onfiles * sizeof(ntable->fdt_ofiles[0]));
1923 * Allocate a new map only if the old is not large enough. It will
1924 * grow at a slower rate than the table as it can map more
1925 * entries than the table can hold.
1927 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1928 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1930 /* copy over the old data and update the pointer */
1931 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1936 * Make sure that ntable is correctly initialized before we replace
1937 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1940 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1943 * Free the old file table when not shared by other threads or processes.
1944 * The old file table is considered to be shared when either are true:
1945 * - The process has more than one thread.
1946 * - The file descriptor table has been shared via fdshare().
1948 * When shared, the old file table will be placed on a freelist
1949 * which will be processed when the struct filedesc is released.
1951 * Note that if onfiles == NDFILE, we're dealing with the original
1952 * static allocation contained within (struct filedesc0 *)fdp,
1953 * which must not be freed.
1955 if (onfiles > NDFILE) {
1957 * Note we may be called here from fdinit while allocating a
1958 * table for a new process in which case ->p_fd points
1961 if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1962 free(otable, M_FILEDESC);
1964 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1965 fdp0 = (struct filedesc0 *)fdp;
1966 ft->ft_table = otable;
1967 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1971 * The map does not have the same possibility of threads still
1972 * holding references to it. So always free it as long as it
1973 * does not reference the original static allocation.
1975 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1976 free(omap, M_FILEDESC);
1980 * Allocate a file descriptor for the process.
1983 fdalloc(struct thread *td, int minfd, int *result)
1985 struct proc *p = td->td_proc;
1986 struct filedesc *fdp = p->p_fd;
1987 int fd, maxfd, allocfd;
1992 FILEDESC_XLOCK_ASSERT(fdp);
1994 if (fdp->fd_freefile > minfd)
1995 minfd = fdp->fd_freefile;
1997 maxfd = getmaxfd(td);
2000 * Search the bitmap for a free descriptor starting at minfd.
2001 * If none is found, grow the file table.
2003 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
2004 if (__predict_false(fd >= maxfd))
2006 if (__predict_false(fd >= fdp->fd_nfiles)) {
2007 allocfd = min(fd * 2, maxfd);
2009 if (RACCT_ENABLED()) {
2010 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
2016 * fd is already equal to first free descriptor >= minfd, so
2017 * we only need to grow the table and we are done.
2019 fdgrowtable_exp(fdp, allocfd);
2023 * Perform some sanity checks, then mark the file descriptor as
2024 * used and return it to the caller.
2026 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
2027 ("invalid descriptor %d", fd));
2028 KASSERT(!fdisused(fdp, fd),
2029 ("fd_first_free() returned non-free descriptor"));
2030 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
2031 ("file descriptor isn't free"));
2038 * Allocate n file descriptors for the process.
2041 fdallocn(struct thread *td, int minfd, int *fds, int n)
2043 struct proc *p = td->td_proc;
2044 struct filedesc *fdp = p->p_fd;
2047 FILEDESC_XLOCK_ASSERT(fdp);
2049 for (i = 0; i < n; i++)
2050 if (fdalloc(td, 0, &fds[i]) != 0)
2054 for (i--; i >= 0; i--)
2055 fdunused(fdp, fds[i]);
2063 * Create a new open file structure and allocate a file descriptor for the
2064 * process that refers to it. We add one reference to the file for the
2065 * descriptor table and one reference for resultfp. This is to prevent us
2066 * being preempted and the entry in the descriptor table closed after we
2067 * release the FILEDESC lock.
2070 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
2071 struct filecaps *fcaps)
2076 MPASS(resultfp != NULL);
2077 MPASS(resultfd != NULL);
2079 error = _falloc_noinstall(td, &fp, 2);
2080 if (__predict_false(error != 0)) {
2084 error = finstall_refed(td, fp, &fd, flags, fcaps);
2085 if (__predict_false(error != 0)) {
2086 falloc_abort(td, fp);
2097 * Create a new open file structure without allocating a file descriptor.
2100 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2103 int maxuserfiles = maxfiles - (maxfiles / 20);
2105 static struct timeval lastfail;
2108 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2111 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2112 if ((openfiles_new >= maxuserfiles &&
2113 priv_check(td, PRIV_MAXFILES) != 0) ||
2114 openfiles_new >= maxfiles) {
2115 atomic_subtract_int(&openfiles, 1);
2116 if (ppsratecheck(&lastfail, &curfail, 1)) {
2117 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2118 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2122 fp = uma_zalloc(file_zone, M_WAITOK);
2123 bzero(fp, sizeof(*fp));
2124 refcount_init(&fp->f_count, n);
2125 fp->f_cred = crhold(td->td_ucred);
2126 fp->f_ops = &badfileops;
2132 falloc_abort(struct thread *td, struct file *fp)
2136 * For assertion purposes.
2138 refcount_init(&fp->f_count, 0);
2143 * Install a file in a file descriptor table.
2146 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2147 struct filecaps *fcaps)
2149 struct filedescent *fde;
2153 filecaps_validate(fcaps, __func__);
2154 FILEDESC_XLOCK_ASSERT(fdp);
2156 fde = &fdp->fd_ofiles[fd];
2158 seqc_write_begin(&fde->fde_seqc);
2161 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2163 filecaps_move(fcaps, &fde->fde_caps);
2165 filecaps_fill(&fde->fde_caps);
2167 seqc_write_end(&fde->fde_seqc);
2172 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2173 struct filecaps *fcaps)
2175 struct filedesc *fdp = td->td_proc->p_fd;
2180 FILEDESC_XLOCK(fdp);
2181 error = fdalloc(td, 0, fd);
2182 if (__predict_true(error == 0)) {
2183 _finstall(fdp, fp, *fd, flags, fcaps);
2185 FILEDESC_XUNLOCK(fdp);
2190 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2191 struct filecaps *fcaps)
2199 error = finstall_refed(td, fp, fd, flags, fcaps);
2200 if (__predict_false(error != 0)) {
2207 * Build a new filedesc structure from another.
2209 * If fdp is not NULL, return with it shared locked.
2212 fdinit(struct filedesc *fdp, bool prepfiles, int *lastfile)
2214 struct filedesc0 *newfdp0;
2215 struct filedesc *newfdp;
2218 MPASS(lastfile != NULL);
2220 MPASS(lastfile == NULL);
2222 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2223 newfdp = &newfdp0->fd_fd;
2225 /* Create the file descriptor table. */
2226 FILEDESC_LOCK_INIT(newfdp);
2227 refcount_init(&newfdp->fd_refcnt, 1);
2228 refcount_init(&newfdp->fd_holdcnt, 1);
2229 newfdp->fd_map = newfdp0->fd_dmap;
2230 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2231 newfdp->fd_files->fdt_nfiles = NDFILE;
2236 FILEDESC_SLOCK(fdp);
2238 FILEDESC_SUNLOCK(fdp);
2243 *lastfile = fdlastfile(fdp);
2244 if (*lastfile < newfdp->fd_nfiles)
2246 FILEDESC_SUNLOCK(fdp);
2247 fdgrowtable(newfdp, *lastfile + 1);
2248 FILEDESC_SLOCK(fdp);
2255 * Build a pwddesc structure from another.
2256 * Copy the current, root, and jail root vnode references.
2258 * If pdp is not NULL, return with it shared locked.
2261 pdinit(struct pwddesc *pdp, bool keeplock)
2263 struct pwddesc *newpdp;
2266 newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2268 PWDDESC_LOCK_INIT(newpdp);
2269 refcount_init(&newpdp->pd_refcount, 1);
2270 newpdp->pd_cmask = CMASK;
2273 newpwd = pwd_alloc();
2274 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2279 newpwd = pwd_hold_pwddesc(pdp);
2280 smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2282 PWDDESC_XUNLOCK(pdp);
2287 * Hold either filedesc or pwddesc of the passed process.
2289 * The process lock is used to synchronize against the target exiting and
2292 * Clearing can be ilustrated in 3 steps:
2293 * 1. set the pointer to NULL. Either routine can race against it, hence
2295 * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2296 * race to either still see the pointer or find NULL. It is still safe to
2297 * grab a reference as clearing is stalled.
2298 * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2299 * guaranteed to see NULL, making it safe to finish clearing
2301 static struct filedesc *
2302 fdhold(struct proc *p)
2304 struct filedesc *fdp;
2306 PROC_LOCK_ASSERT(p, MA_OWNED);
2307 fdp = atomic_load_ptr(&p->p_fd);
2309 refcount_acquire(&fdp->fd_holdcnt);
2313 static struct pwddesc *
2314 pdhold(struct proc *p)
2316 struct pwddesc *pdp;
2318 PROC_LOCK_ASSERT(p, MA_OWNED);
2319 pdp = atomic_load_ptr(&p->p_pd);
2321 refcount_acquire(&pdp->pd_refcount);
2326 fddrop(struct filedesc *fdp)
2329 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2330 if (refcount_release(&fdp->fd_holdcnt) == 0)
2334 FILEDESC_LOCK_DESTROY(fdp);
2335 uma_zfree(filedesc0_zone, fdp);
2339 pddrop(struct pwddesc *pdp)
2343 if (refcount_release_if_not_last(&pdp->pd_refcount))
2347 if (refcount_release(&pdp->pd_refcount) == 0) {
2348 PWDDESC_XUNLOCK(pdp);
2351 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2353 PWDDESC_XUNLOCK(pdp);
2356 PWDDESC_LOCK_DESTROY(pdp);
2357 free(pdp, M_PWDDESC);
2361 * Share a filedesc structure.
2364 fdshare(struct filedesc *fdp)
2367 refcount_acquire(&fdp->fd_refcnt);
2372 * Share a pwddesc structure.
2375 pdshare(struct pwddesc *pdp)
2377 refcount_acquire(&pdp->pd_refcount);
2382 * Unshare a filedesc structure, if necessary by making a copy
2385 fdunshare(struct thread *td)
2387 struct filedesc *tmp;
2388 struct proc *p = td->td_proc;
2390 if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2393 tmp = fdcopy(p->p_fd);
2399 * Unshare a pwddesc structure.
2402 pdunshare(struct thread *td)
2404 struct pwddesc *pdp;
2409 if (p->p_pd->pd_refcount == 1)
2412 pdp = pdcopy(p->p_pd);
2418 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2422 td->td_proc->p_fd = fdp;
2426 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2427 * this is to ease callers, not catch errors.
2430 fdcopy(struct filedesc *fdp)
2432 struct filedesc *newfdp;
2433 struct filedescent *nfde, *ofde;
2438 newfdp = fdinit(fdp, true, &lastfile);
2439 /* copy all passable descriptors (i.e. not kqueue) */
2440 newfdp->fd_freefile = -1;
2441 for (i = 0; i <= lastfile; ++i) {
2442 ofde = &fdp->fd_ofiles[i];
2443 if (ofde->fde_file == NULL ||
2444 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2445 !fhold(ofde->fde_file)) {
2446 if (newfdp->fd_freefile == -1)
2447 newfdp->fd_freefile = i;
2450 nfde = &newfdp->fd_ofiles[i];
2452 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2453 fdused_init(newfdp, i);
2455 if (newfdp->fd_freefile == -1)
2456 newfdp->fd_freefile = i;
2457 FILEDESC_SUNLOCK(fdp);
2462 * Copy a pwddesc structure.
2465 pdcopy(struct pwddesc *pdp)
2467 struct pwddesc *newpdp;
2471 newpdp = pdinit(pdp, true);
2472 newpdp->pd_cmask = pdp->pd_cmask;
2473 PWDDESC_XUNLOCK(pdp);
2478 * Copies a filedesc structure, while remapping all file descriptors
2479 * stored inside using a translation table.
2481 * File descriptors are copied over to the new file descriptor table,
2482 * regardless of whether the close-on-exec flag is set.
2485 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2486 struct filedesc **ret)
2488 struct filedesc *newfdp;
2489 struct filedescent *nfde, *ofde;
2490 int error, i, lastfile;
2494 newfdp = fdinit(fdp, true, &lastfile);
2495 if (nfds > lastfile + 1) {
2496 /* New table cannot be larger than the old one. */
2500 /* Copy all passable descriptors (i.e. not kqueue). */
2501 newfdp->fd_freefile = nfds;
2502 for (i = 0; i < nfds; ++i) {
2503 if (fds[i] < 0 || fds[i] > lastfile) {
2504 /* File descriptor out of bounds. */
2508 ofde = &fdp->fd_ofiles[fds[i]];
2509 if (ofde->fde_file == NULL) {
2510 /* Unused file descriptor. */
2514 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2515 /* File descriptor cannot be passed. */
2519 if (!fhold(ofde->fde_file)) {
2523 nfde = &newfdp->fd_ofiles[i];
2525 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2526 fdused_init(newfdp, i);
2528 FILEDESC_SUNLOCK(fdp);
2532 FILEDESC_SUNLOCK(fdp);
2533 fdescfree_remapped(newfdp);
2538 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2539 * one of processes using it exits) and the table used to be shared.
2542 fdclearlocks(struct thread *td)
2544 struct filedesc *fdp;
2545 struct filedesc_to_leader *fdtol;
2555 MPASS(fdtol != NULL);
2557 FILEDESC_XLOCK(fdp);
2558 KASSERT(fdtol->fdl_refcount > 0,
2559 ("filedesc_to_refcount botch: fdl_refcount=%d",
2560 fdtol->fdl_refcount));
2561 if (fdtol->fdl_refcount == 1 &&
2562 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2563 lastfile = fdlastfile(fdp);
2564 for (i = 0; i <= lastfile; i++) {
2565 fp = fdp->fd_ofiles[i].fde_file;
2566 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2569 FILEDESC_XUNLOCK(fdp);
2570 lf.l_whence = SEEK_SET;
2573 lf.l_type = F_UNLCK;
2575 (void) VOP_ADVLOCK(vp,
2576 (caddr_t)p->p_leader, F_UNLCK,
2578 FILEDESC_XLOCK(fdp);
2583 if (fdtol->fdl_refcount == 1) {
2584 if (fdp->fd_holdleaderscount > 0 &&
2585 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2587 * close() or kern_dup() has cleared a reference
2588 * in a shared file descriptor table.
2590 fdp->fd_holdleaderswakeup = 1;
2591 sx_sleep(&fdp->fd_holdleaderscount,
2592 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2595 if (fdtol->fdl_holdcount > 0) {
2597 * Ensure that fdtol->fdl_leader remains
2598 * valid in closef().
2600 fdtol->fdl_wakeup = 1;
2601 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2606 fdtol->fdl_refcount--;
2607 if (fdtol->fdl_refcount == 0 &&
2608 fdtol->fdl_holdcount == 0) {
2609 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2610 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2614 FILEDESC_XUNLOCK(fdp);
2616 free(fdtol, M_FILEDESC_TO_LEADER);
2620 * Release a filedesc structure.
2623 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2625 struct filedesc0 *fdp0;
2626 struct freetable *ft, *tft;
2627 struct filedescent *fde;
2631 KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2632 ("%s: fd table %p carries references", __func__, fdp));
2635 * Serialize with threads iterating over the table, if any.
2637 if (refcount_load(&fdp->fd_holdcnt) > 1) {
2638 FILEDESC_XLOCK(fdp);
2639 FILEDESC_XUNLOCK(fdp);
2642 lastfile = fdlastfile_single(fdp);
2643 for (i = 0; i <= lastfile; i++) {
2644 fde = &fdp->fd_ofiles[i];
2649 (void) closef(fp, td);
2655 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2656 free(fdp->fd_map, M_FILEDESC);
2657 if (fdp->fd_nfiles > NDFILE)
2658 free(fdp->fd_files, M_FILEDESC);
2660 fdp0 = (struct filedesc0 *)fdp;
2661 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2662 free(ft->ft_table, M_FILEDESC);
2668 fdescfree(struct thread *td)
2671 struct filedesc *fdp;
2678 if (RACCT_ENABLED())
2679 racct_set_unlocked(p, RACCT_NOFILE, 0);
2682 if (p->p_fdtol != NULL)
2686 * Check fdhold for an explanation.
2688 atomic_store_ptr(&p->p_fd, NULL);
2689 atomic_thread_fence_seq_cst();
2690 PROC_WAIT_UNLOCKED(p);
2692 if (refcount_release(&fdp->fd_refcnt) == 0)
2695 fdescfree_fds(td, fdp, 1);
2699 pdescfree(struct thread *td)
2702 struct pwddesc *pdp;
2709 * Check pdhold for an explanation.
2711 atomic_store_ptr(&p->p_pd, NULL);
2712 atomic_thread_fence_seq_cst();
2713 PROC_WAIT_UNLOCKED(p);
2719 fdescfree_remapped(struct filedesc *fdp)
2722 /* fdescfree_fds() asserts that fd_refcnt == 0. */
2723 if (!refcount_release(&fdp->fd_refcnt))
2724 panic("%s: fd table %p has extra references", __func__, fdp);
2726 fdescfree_fds(curthread, fdp, 0);
2730 * For setugid programs, we don't want to people to use that setugidness
2731 * to generate error messages which write to a file which otherwise would
2732 * otherwise be off-limits to the process. We check for filesystems where
2733 * the vnode can change out from under us after execve (like [lin]procfs).
2735 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2736 * sufficient. We also don't check for setugidness since we know we are.
2739 is_unsafe(struct file *fp)
2743 if (fp->f_type != DTYPE_VNODE)
2747 return ((vp->v_vflag & VV_PROCDEP) != 0);
2751 * Make this setguid thing safe, if at all possible.
2754 fdsetugidsafety(struct thread *td)
2756 struct filedesc *fdp;
2760 fdp = td->td_proc->p_fd;
2761 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2762 ("the fdtable should not be shared"));
2763 MPASS(fdp->fd_nfiles >= 3);
2764 for (i = 0; i <= 2; i++) {
2765 fp = fdp->fd_ofiles[i].fde_file;
2766 if (fp != NULL && is_unsafe(fp)) {
2767 FILEDESC_XLOCK(fdp);
2768 knote_fdclose(td, i);
2770 * NULL-out descriptor prior to close to avoid
2771 * a race while close blocks.
2774 FILEDESC_XUNLOCK(fdp);
2775 (void) closef(fp, td);
2781 * If a specific file object occupies a specific file descriptor, close the
2782 * file descriptor entry and drop a reference on the file object. This is a
2783 * convenience function to handle a subsequent error in a function that calls
2784 * falloc() that handles the race that another thread might have closed the
2785 * file descriptor out from under the thread creating the file object.
2788 fdclose(struct thread *td, struct file *fp, int idx)
2790 struct filedesc *fdp = td->td_proc->p_fd;
2792 FILEDESC_XLOCK(fdp);
2793 if (fdp->fd_ofiles[idx].fde_file == fp) {
2795 FILEDESC_XUNLOCK(fdp);
2798 FILEDESC_XUNLOCK(fdp);
2802 * Close any files on exec?
2805 fdcloseexec(struct thread *td)
2807 struct filedesc *fdp;
2808 struct filedescent *fde;
2812 fdp = td->td_proc->p_fd;
2813 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2814 ("the fdtable should not be shared"));
2815 lastfile = fdlastfile_single(fdp);
2816 for (i = 0; i <= lastfile; i++) {
2817 fde = &fdp->fd_ofiles[i];
2819 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2820 (fde->fde_flags & UF_EXCLOSE))) {
2821 FILEDESC_XLOCK(fdp);
2823 (void) closefp(fdp, i, fp, td, false, false);
2824 FILEDESC_UNLOCK_ASSERT(fdp);
2830 * It is unsafe for set[ug]id processes to be started with file
2831 * descriptors 0..2 closed, as these descriptors are given implicit
2832 * significance in the Standard C library. fdcheckstd() will create a
2833 * descriptor referencing /dev/null for each of stdin, stdout, and
2834 * stderr that is not already open.
2837 fdcheckstd(struct thread *td)
2839 struct filedesc *fdp;
2841 int i, error, devnull;
2843 fdp = td->td_proc->p_fd;
2844 KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2845 ("the fdtable should not be shared"));
2846 MPASS(fdp->fd_nfiles >= 3);
2848 for (i = 0; i <= 2; i++) {
2849 if (fdp->fd_ofiles[i].fde_file != NULL)
2852 save = td->td_retval[0];
2853 if (devnull != -1) {
2854 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2856 error = kern_openat(td, AT_FDCWD, "/dev/null",
2857 UIO_SYSSPACE, O_RDWR, 0);
2859 devnull = td->td_retval[0];
2860 KASSERT(devnull == i, ("we didn't get our fd"));
2863 td->td_retval[0] = save;
2871 * Internal form of close. Decrement reference count on file structure.
2872 * Note: td may be NULL when closing a file that was being passed in a
2876 closef(struct file *fp, struct thread *td)
2880 struct filedesc_to_leader *fdtol;
2881 struct filedesc *fdp;
2886 * POSIX record locking dictates that any close releases ALL
2887 * locks owned by this process. This is handled by setting
2888 * a flag in the unlock to free ONLY locks obeying POSIX
2889 * semantics, and not to free BSD-style file locks.
2890 * If the descriptor was in a message, POSIX-style locks
2891 * aren't passed with the descriptor, and the thread pointer
2892 * will be NULL. Callers should be careful only to pass a
2893 * NULL thread pointer when there really is no owning
2894 * context that might have locks, or the locks will be
2897 if (fp->f_type == DTYPE_VNODE) {
2899 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2900 lf.l_whence = SEEK_SET;
2903 lf.l_type = F_UNLCK;
2904 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2905 F_UNLCK, &lf, F_POSIX);
2907 fdtol = td->td_proc->p_fdtol;
2908 if (fdtol != NULL) {
2910 * Handle special case where file descriptor table is
2911 * shared between multiple process leaders.
2913 fdp = td->td_proc->p_fd;
2914 FILEDESC_XLOCK(fdp);
2915 for (fdtol = fdtol->fdl_next;
2916 fdtol != td->td_proc->p_fdtol;
2917 fdtol = fdtol->fdl_next) {
2918 if ((fdtol->fdl_leader->p_flag &
2921 fdtol->fdl_holdcount++;
2922 FILEDESC_XUNLOCK(fdp);
2923 lf.l_whence = SEEK_SET;
2926 lf.l_type = F_UNLCK;
2928 (void) VOP_ADVLOCK(vp,
2929 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2931 FILEDESC_XLOCK(fdp);
2932 fdtol->fdl_holdcount--;
2933 if (fdtol->fdl_holdcount == 0 &&
2934 fdtol->fdl_wakeup != 0) {
2935 fdtol->fdl_wakeup = 0;
2939 FILEDESC_XUNLOCK(fdp);
2942 return (fdrop_close(fp, td));
2946 * Hack for file descriptor passing code.
2949 closef_nothread(struct file *fp)
2956 * Initialize the file pointer with the specified properties.
2958 * The ops are set with release semantics to be certain that the flags, type,
2959 * and data are visible when ops is. This is to prevent ops methods from being
2960 * called with bad data.
2963 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2968 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2972 finit_vnode(struct file *fp, u_int flag, void *data, struct fileops *ops)
2974 fp->f_seqcount[UIO_READ] = 1;
2975 fp->f_seqcount[UIO_WRITE] = 1;
2976 finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2981 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2982 struct file **fpp, struct filecaps *havecapsp)
2984 struct filedescent *fde;
2987 FILEDESC_LOCK_ASSERT(fdp);
2990 fde = fdeget_locked(fdp, fd);
2997 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
3002 if (havecapsp != NULL)
3003 filecaps_copy(&fde->fde_caps, havecapsp, true);
3005 *fpp = fde->fde_file;
3013 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
3014 struct file **fpp, struct filecaps *havecapsp)
3016 struct filedesc *fdp = td->td_proc->p_fd;
3018 #ifndef CAPABILITIES
3019 error = fget_unlocked(fdp, fd, needrightsp, fpp);
3020 if (havecapsp != NULL && error == 0)
3021 filecaps_fill(havecapsp);
3028 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
3032 if (havecapsp != NULL) {
3033 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
3034 havecapsp, false)) {
3040 if (!fd_modified(fdp, fd, seq))
3049 FILEDESC_SLOCK(fdp);
3050 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
3051 if (error == 0 && !fhold(*fpp))
3053 FILEDESC_SUNLOCK(fdp);
3060 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3062 const struct filedescent *fde;
3063 const struct fdescenttbl *fdt;
3064 struct filedesc *fdp;
3067 const cap_rights_t *haverights;
3068 cap_rights_t rights;
3071 VFS_SMR_ASSERT_ENTERED();
3073 rights = *ndp->ni_rightsneeded;
3074 cap_rights_set_one(&rights, CAP_LOOKUP);
3076 fdp = curproc->p_fd;
3077 fdt = fdp->fd_files;
3078 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3080 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3081 fde = &fdt->fdt_ofiles[fd];
3082 haverights = cap_rights_fde_inline(fde);
3084 if (__predict_false(fp == NULL))
3086 if (__predict_false(cap_check_inline_transient(haverights, &rights)))
3088 *fsearch = ((fp->f_flag & FSEARCH) != 0);
3090 if (__predict_false(vp == NULL)) {
3093 if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
3097 * Use an acquire barrier to force re-reading of fdt so it is
3098 * refreshed for verification.
3100 atomic_thread_fence_acq();
3101 fdt = fdp->fd_files;
3102 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
3105 * If file descriptor doesn't have all rights,
3106 * all lookups relative to it must also be
3107 * strictly relative.
3109 * Not yet supported by fast path.
3112 if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3113 ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3114 ndp->ni_filecaps.fc_nioctls != -1) {
3116 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
3126 fgetvp_lookup_smr(int fd, struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3128 const struct fdescenttbl *fdt;
3129 struct filedesc *fdp;
3133 VFS_SMR_ASSERT_ENTERED();
3135 fdp = curproc->p_fd;
3136 fdt = fdp->fd_files;
3137 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3139 fp = fdt->fdt_ofiles[fd].fde_file;
3140 if (__predict_false(fp == NULL))
3142 *fsearch = ((fp->f_flag & FSEARCH) != 0);
3144 if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
3148 * Use an acquire barrier to force re-reading of fdt so it is
3149 * refreshed for verification.
3151 atomic_thread_fence_acq();
3152 fdt = fdp->fd_files;
3153 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3155 filecaps_fill(&ndp->ni_filecaps);
3162 fgetvp_lookup(int fd, struct nameidata *ndp, struct vnode **vpp)
3167 struct componentname *cnp;
3168 cap_rights_t rights;
3172 rights = *ndp->ni_rightsneeded;
3173 cap_rights_set_one(&rights, CAP_LOOKUP);
3176 error = fget_cap(td, ndp->ni_dirfd, &rights, &fp, &ndp->ni_filecaps);
3177 if (__predict_false(error != 0))
3179 if (__predict_false(fp->f_ops == &badfileops)) {
3184 if (__predict_false(vp == NULL)) {
3190 * XXX does not check for VDIR, handled by namei_setup
3192 if ((fp->f_flag & FSEARCH) != 0)
3193 cnp->cn_flags |= NOEXECCHECK;
3198 * If file descriptor doesn't have all rights,
3199 * all lookups relative to it must also be
3200 * strictly relative.
3203 if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3204 ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3205 ndp->ni_filecaps.fc_nioctls != -1) {
3206 ndp->ni_lcf |= NI_LCF_STRICTRELATIVE;
3207 ndp->ni_resflags |= NIRES_STRICTREL;
3212 * TODO: avoid copying ioctl caps if it can be helped to begin with
3214 if ((cnp->cn_flags & WANTIOCTLCAPS) == 0)
3215 filecaps_free_ioctl(&ndp->ni_filecaps);
3221 filecaps_free(&ndp->ni_filecaps);
3227 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3228 struct file **fpp, seqc_t *seqp)
3231 const struct filedescent *fde;
3233 const struct fdescenttbl *fdt;
3237 cap_rights_t haverights;
3241 fdt = fdp->fd_files;
3242 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3245 * Fetch the descriptor locklessly. We avoid fdrop() races by
3246 * never raising a refcount above 0. To accomplish this we have
3247 * to use a cmpset loop rather than an atomic_add. The descriptor
3248 * must be re-verified once we acquire a reference to be certain
3249 * that the identity is still correct and we did not lose a race
3250 * due to preemption.
3254 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3255 fde = &fdt->fdt_ofiles[fd];
3256 haverights = *cap_rights_fde_inline(fde);
3258 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
3261 fp = fdt->fdt_ofiles[fd].fde_file;
3266 error = cap_check_inline(&haverights, needrightsp);
3270 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3272 * Force a reload. Other thread could reallocate the
3273 * table before this fd was closed, so it is possible
3274 * that there is a stale fp pointer in cached version.
3276 fdt = atomic_load_ptr(&fdp->fd_files);
3280 * Use an acquire barrier to force re-reading of fdt so it is
3281 * refreshed for verification.
3283 atomic_thread_fence_acq();
3284 fdt = fdp->fd_files;
3286 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
3288 if (fp == fdt->fdt_ofiles[fd].fde_file)
3291 fdrop(fp, curthread);
3303 * See the comments in fget_unlocked_seq for an explanation of how this works.
3305 * This is a simplified variant which bails out to the aforementioned routine
3306 * if anything goes wrong. In practice this only happens when userspace is
3307 * racing with itself.
3310 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3314 const struct filedescent *fde;
3316 const struct fdescenttbl *fdt;
3320 const cap_rights_t *haverights;
3323 fdt = fdp->fd_files;
3324 if (__predict_false((u_int)fd >= fdt->fdt_nfiles)) {
3329 seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3330 fde = &fdt->fdt_ofiles[fd];
3331 haverights = cap_rights_fde_inline(fde);
3334 fp = fdt->fdt_ofiles[fd].fde_file;
3336 if (__predict_false(fp == NULL))
3339 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3342 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3346 * Use an acquire barrier to force re-reading of fdt so it is
3347 * refreshed for verification.
3349 atomic_thread_fence_acq();
3350 fdt = fdp->fd_files;
3352 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
3354 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3360 fdrop(fp, curthread);
3363 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
3367 * Translate fd -> file when the caller guarantees the file descriptor table
3368 * can't be changed by others.
3370 * Note this does not mean the file object itself is only visible to the caller,
3371 * merely that it wont disappear without having to be referenced.
3373 * Must be paired with fput_only_user.
3377 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3380 const struct filedescent *fde;
3381 const struct fdescenttbl *fdt;
3382 const cap_rights_t *haverights;
3386 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3389 if (__predict_false(fd >= fdp->fd_nfiles))
3392 fdt = fdp->fd_files;
3393 fde = &fdt->fdt_ofiles[fd];
3395 if (__predict_false(fp == NULL))
3397 MPASS(refcount_load(&fp->f_count) > 0);
3398 haverights = cap_rights_fde_inline(fde);
3399 error = cap_check_inline(haverights, needrightsp);
3400 if (__predict_false(error != 0))
3407 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3412 MPASS(FILEDESC_IS_ONLY_USER(fdp));
3415 if (__predict_false(fd >= fdp->fd_nfiles))
3418 fp = fdp->fd_ofiles[fd].fde_file;
3419 if (__predict_false(fp == NULL))
3422 MPASS(refcount_load(&fp->f_count) > 0);
3429 * Extract the file pointer associated with the specified descriptor for the
3430 * current user process.
3432 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3435 * File's rights will be checked against the capability rights mask.
3437 * If an error occurred the non-zero error is returned and *fpp is set to
3438 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
3439 * responsible for fdrop().
3442 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3443 cap_rights_t *needrightsp)
3445 struct filedesc *fdp;
3450 fdp = td->td_proc->p_fd;
3451 error = fget_unlocked(fdp, fd, needrightsp, &fp);
3452 if (__predict_false(error != 0))
3454 if (__predict_false(fp->f_ops == &badfileops)) {
3460 * FREAD and FWRITE failure return EBADF as per POSIX.
3466 if ((fp->f_flag & flags) == 0)
3470 if (fp->f_ops != &path_fileops &&
3471 ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3472 (fp->f_flag & FWRITE) != 0))
3478 KASSERT(0, ("wrong flags"));
3491 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3494 return (_fget(td, fd, fpp, 0, rightsp));
3498 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
3502 #ifndef CAPABILITIES
3503 error = _fget(td, fd, fpp, 0, rightsp);
3504 if (maxprotp != NULL)
3505 *maxprotp = VM_PROT_ALL;
3508 cap_rights_t fdrights;
3509 struct filedesc *fdp;
3514 fdp = td->td_proc->p_fd;
3515 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3517 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
3518 if (__predict_false(error != 0))
3520 if (__predict_false(fp->f_ops == &badfileops)) {
3524 if (maxprotp != NULL)
3525 fdrights = *cap_rights(fdp, fd);
3526 if (!fd_modified(fdp, fd, seq))
3532 * If requested, convert capability rights to access flags.
3534 if (maxprotp != NULL)
3535 *maxprotp = cap_rights_to_vmprot(&fdrights);
3542 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3545 return (_fget(td, fd, fpp, FREAD, rightsp));
3549 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3552 return (_fget(td, fd, fpp, FWRITE, rightsp));
3556 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
3559 struct filedesc *fdp = td->td_proc->p_fd;
3560 #ifndef CAPABILITIES
3561 return (fget_unlocked(fdp, fd, rightsp, fpp));
3568 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3570 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
3573 error = cap_fcntl_check(fdp, fd, needfcntl);
3574 if (!fd_modified(fdp, fd, seq))
3588 * Like fget() but loads the underlying vnode, or returns an error if the
3589 * descriptor does not represent a vnode. Note that pipes use vnodes but
3590 * never have VM objects. The returned vnode will be vref()'d.
3592 * XXX: what about the unused flags ?
3595 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3602 error = _fget(td, fd, &fp, flags, needrightsp);
3605 if (fp->f_vnode == NULL) {
3617 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3620 return (_fgetvp(td, fd, 0, rightsp, vpp));
3624 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3625 struct filecaps *havecaps, struct vnode **vpp)
3627 struct filecaps caps;
3631 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3634 if (fp->f_ops == &badfileops) {
3638 if (fp->f_vnode == NULL) {
3650 filecaps_free(&caps);
3656 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3659 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3663 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3666 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3671 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3675 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3680 * Handle the last reference to a file being closed.
3682 * Without the noinline attribute clang keeps inlining the func thorough this
3683 * file when fdrop is used.
3686 _fdrop(struct file *fp, struct thread *td)
3692 count = refcount_load(&fp->f_count);
3694 panic("fdrop: fp %p count %d", fp, count);
3696 error = fo_close(fp, td);
3697 atomic_subtract_int(&openfiles, 1);
3699 free(fp->f_advice, M_FADVISE);
3700 uma_zfree(file_zone, fp);
3706 * Apply an advisory lock on a file descriptor.
3708 * Just attempt to get a record lock of the requested type on the entire file
3709 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3711 #ifndef _SYS_SYSPROTO_H_
3719 sys_flock(struct thread *td, struct flock_args *uap)
3726 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3730 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3733 if (fp->f_ops == &path_fileops) {
3739 lf.l_whence = SEEK_SET;
3742 if (uap->how & LOCK_UN) {
3743 lf.l_type = F_UNLCK;
3744 atomic_clear_int(&fp->f_flag, FHASLOCK);
3745 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3748 if (uap->how & LOCK_EX)
3749 lf.l_type = F_WRLCK;
3750 else if (uap->how & LOCK_SH)
3751 lf.l_type = F_RDLCK;
3756 atomic_set_int(&fp->f_flag, FHASLOCK);
3757 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3758 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3764 * Duplicate the specified descriptor to a free descriptor.
3767 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3768 int openerror, int *indxp)
3770 struct filedescent *newfde, *oldfde;
3775 KASSERT(openerror == ENODEV || openerror == ENXIO,
3776 ("unexpected error %d in %s", openerror, __func__));
3779 * If the to-be-dup'd fd number is greater than the allowed number
3780 * of file descriptors, or the fd to be dup'd has already been
3781 * closed, then reject.
3783 FILEDESC_XLOCK(fdp);
3784 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3785 FILEDESC_XUNLOCK(fdp);
3789 error = fdalloc(td, 0, &indx);
3791 FILEDESC_XUNLOCK(fdp);
3796 * There are two cases of interest here.
3798 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3800 * For ENXIO steal away the file structure from (dfd) and store it in
3801 * (indx). (dfd) is effectively closed by this operation.
3803 switch (openerror) {
3806 * Check that the mode the file is being opened for is a
3807 * subset of the mode of the existing descriptor.
3809 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3810 fdunused(fdp, indx);
3811 FILEDESC_XUNLOCK(fdp);
3815 fdunused(fdp, indx);
3816 FILEDESC_XUNLOCK(fdp);
3819 newfde = &fdp->fd_ofiles[indx];
3820 oldfde = &fdp->fd_ofiles[dfd];
3821 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3823 seqc_write_begin(&newfde->fde_seqc);
3825 memcpy(newfde, oldfde, fde_change_size);
3826 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3829 seqc_write_end(&newfde->fde_seqc);
3834 * Steal away the file pointer from dfd and stuff it into indx.
3836 newfde = &fdp->fd_ofiles[indx];
3837 oldfde = &fdp->fd_ofiles[dfd];
3839 seqc_write_begin(&newfde->fde_seqc);
3841 memcpy(newfde, oldfde, fde_change_size);
3842 oldfde->fde_file = NULL;
3845 seqc_write_end(&newfde->fde_seqc);
3849 FILEDESC_XUNLOCK(fdp);
3855 * This sysctl determines if we will allow a process to chroot(2) if it
3856 * has a directory open:
3857 * 0: disallowed for all processes.
3858 * 1: allowed for processes that were not already chroot(2)'ed.
3859 * 2: allowed for all processes.
3862 static int chroot_allow_open_directories = 1;
3864 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3865 &chroot_allow_open_directories, 0,
3866 "Allow a process to chroot(2) if it has a directory open");
3869 * Helper function for raised chroot(2) security function: Refuse if
3870 * any filedescriptors are open directories.
3873 chroot_refuse_vdir_fds(struct filedesc *fdp)
3879 FILEDESC_LOCK_ASSERT(fdp);
3881 lastfile = fdlastfile(fdp);
3882 for (fd = 0; fd <= lastfile; fd++) {
3883 fp = fget_locked(fdp, fd);
3886 if (fp->f_type == DTYPE_VNODE) {
3888 if (vp->v_type == VDIR)
3896 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3899 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3900 vrefact(oldpwd->pwd_cdir);
3901 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3904 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3905 vrefact(oldpwd->pwd_rdir);
3906 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3909 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3910 vrefact(oldpwd->pwd_jdir);
3911 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3916 pwd_hold_pwddesc(struct pwddesc *pdp)
3920 PWDDESC_ASSERT_XLOCKED(pdp);
3921 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3923 refcount_acquire(&pwd->pwd_refcount);
3928 pwd_hold_smr(struct pwd *pwd)
3932 if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3939 pwd_hold(struct thread *td)
3941 struct pwddesc *pdp;
3944 pdp = td->td_proc->p_pd;
3947 pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3948 if (pwd_hold_smr(pwd)) {
3954 pwd = pwd_hold_pwddesc(pdp);
3956 PWDDESC_XUNLOCK(pdp);
3961 pwd_hold_proc(struct proc *p)
3963 struct pwddesc *pdp;
3966 PROC_ASSERT_HELD(p);
3973 pwd = pwd_hold_pwddesc(pdp);
3975 PWDDESC_XUNLOCK(pdp);
3985 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3986 bzero(pwd, sizeof(*pwd));
3987 refcount_init(&pwd->pwd_refcount, 1);
3992 pwd_drop(struct pwd *pwd)
3995 if (!refcount_release(&pwd->pwd_refcount))
3998 if (pwd->pwd_cdir != NULL)
3999 vrele(pwd->pwd_cdir);
4000 if (pwd->pwd_rdir != NULL)
4001 vrele(pwd->pwd_rdir);
4002 if (pwd->pwd_jdir != NULL)
4003 vrele(pwd->pwd_jdir);
4004 uma_zfree_smr(pwd_zone, pwd);
4008 * The caller is responsible for invoking priv_check() and
4009 * mac_vnode_check_chroot() to authorize this operation.
4012 pwd_chroot(struct thread *td, struct vnode *vp)
4014 struct pwddesc *pdp;
4015 struct filedesc *fdp;
4016 struct pwd *newpwd, *oldpwd;
4019 fdp = td->td_proc->p_fd;
4020 pdp = td->td_proc->p_pd;
4021 newpwd = pwd_alloc();
4022 FILEDESC_SLOCK(fdp);
4024 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4025 if (chroot_allow_open_directories == 0 ||
4026 (chroot_allow_open_directories == 1 &&
4027 oldpwd->pwd_rdir != rootvnode)) {
4028 error = chroot_refuse_vdir_fds(fdp);
4029 FILEDESC_SUNLOCK(fdp);
4031 PWDDESC_XUNLOCK(pdp);
4036 FILEDESC_SUNLOCK(fdp);
4040 newpwd->pwd_rdir = vp;
4041 if (oldpwd->pwd_jdir == NULL) {
4043 newpwd->pwd_jdir = vp;
4045 pwd_fill(oldpwd, newpwd);
4046 pwd_set(pdp, newpwd);
4047 PWDDESC_XUNLOCK(pdp);
4053 pwd_chdir(struct thread *td, struct vnode *vp)
4055 struct pwddesc *pdp;
4056 struct pwd *newpwd, *oldpwd;
4058 VNPASS(vp->v_usecount > 0, vp);
4060 newpwd = pwd_alloc();
4061 pdp = td->td_proc->p_pd;
4063 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4064 newpwd->pwd_cdir = vp;
4065 pwd_fill(oldpwd, newpwd);
4066 pwd_set(pdp, newpwd);
4067 PWDDESC_XUNLOCK(pdp);
4072 * jail_attach(2) changes both root and working directories.
4075 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
4077 struct pwddesc *pdp;
4078 struct filedesc *fdp;
4079 struct pwd *newpwd, *oldpwd;
4082 fdp = td->td_proc->p_fd;
4083 pdp = td->td_proc->p_pd;
4084 newpwd = pwd_alloc();
4085 FILEDESC_SLOCK(fdp);
4087 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4088 error = chroot_refuse_vdir_fds(fdp);
4089 FILEDESC_SUNLOCK(fdp);
4091 PWDDESC_XUNLOCK(pdp);
4097 newpwd->pwd_rdir = vp;
4099 newpwd->pwd_cdir = vp;
4100 if (oldpwd->pwd_jdir == NULL) {
4102 newpwd->pwd_jdir = vp;
4104 pwd_fill(oldpwd, newpwd);
4105 pwd_set(pdp, newpwd);
4106 PWDDESC_XUNLOCK(pdp);
4112 pwd_ensure_dirs(void)
4114 struct pwddesc *pdp;
4115 struct pwd *oldpwd, *newpwd;
4117 pdp = curproc->p_pd;
4119 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4120 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
4121 PWDDESC_XUNLOCK(pdp);
4124 PWDDESC_XUNLOCK(pdp);
4126 newpwd = pwd_alloc();
4128 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4129 pwd_fill(oldpwd, newpwd);
4130 if (newpwd->pwd_cdir == NULL) {
4132 newpwd->pwd_cdir = rootvnode;
4134 if (newpwd->pwd_rdir == NULL) {
4136 newpwd->pwd_rdir = rootvnode;
4138 pwd_set(pdp, newpwd);
4139 PWDDESC_XUNLOCK(pdp);
4144 pwd_set_rootvnode(void)
4146 struct pwddesc *pdp;
4147 struct pwd *oldpwd, *newpwd;
4149 pdp = curproc->p_pd;
4151 newpwd = pwd_alloc();
4153 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4155 newpwd->pwd_cdir = rootvnode;
4157 newpwd->pwd_rdir = rootvnode;
4158 pwd_fill(oldpwd, newpwd);
4159 pwd_set(pdp, newpwd);
4160 PWDDESC_XUNLOCK(pdp);
4165 * Scan all active processes and prisons to see if any of them have a current
4166 * or root directory of `olddp'. If so, replace them with the new mount point.
4169 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
4171 struct pwddesc *pdp;
4172 struct pwd *newpwd, *oldpwd;
4177 if (vrefcnt(olddp) == 1)
4180 newpwd = pwd_alloc();
4181 sx_slock(&allproc_lock);
4182 FOREACH_PROC_IN_SYSTEM(p) {
4189 oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4190 if (oldpwd == NULL ||
4191 (oldpwd->pwd_cdir != olddp &&
4192 oldpwd->pwd_rdir != olddp &&
4193 oldpwd->pwd_jdir != olddp)) {
4194 PWDDESC_XUNLOCK(pdp);
4198 if (oldpwd->pwd_cdir == olddp) {
4200 newpwd->pwd_cdir = newdp;
4202 if (oldpwd->pwd_rdir == olddp) {
4204 newpwd->pwd_rdir = newdp;
4206 if (oldpwd->pwd_jdir == olddp) {
4208 newpwd->pwd_jdir = newdp;
4210 pwd_fill(oldpwd, newpwd);
4211 pwd_set(pdp, newpwd);
4212 PWDDESC_XUNLOCK(pdp);
4215 newpwd = pwd_alloc();
4217 sx_sunlock(&allproc_lock);
4219 if (rootvnode == olddp) {
4224 mtx_lock(&prison0.pr_mtx);
4225 if (prison0.pr_root == olddp) {
4227 prison0.pr_root = newdp;
4230 mtx_unlock(&prison0.pr_mtx);
4231 sx_slock(&allprison_lock);
4232 TAILQ_FOREACH(pr, &allprison, pr_list) {
4233 mtx_lock(&pr->pr_mtx);
4234 if (pr->pr_root == olddp) {
4236 pr->pr_root = newdp;
4239 mtx_unlock(&pr->pr_mtx);
4241 sx_sunlock(&allprison_lock);
4247 descrip_check_write_mp(struct filedesc *fdp, struct mount *mp)
4251 int error, i, lastfile;
4254 FILEDESC_SLOCK(fdp);
4255 lastfile = fdlastfile(fdp);
4256 for (i = 0; i <= lastfile; i++) {
4257 fp = fdp->fd_ofiles[i].fde_file;
4258 if (fp->f_type != DTYPE_VNODE ||
4259 (atomic_load_int(&fp->f_flag) & FWRITE) == 0)
4262 if (vp->v_mount == mp) {
4267 FILEDESC_SUNLOCK(fdp);
4271 struct filedesc_to_leader *
4272 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp,
4273 struct proc *leader)
4275 struct filedesc_to_leader *fdtol;
4277 fdtol = malloc(sizeof(struct filedesc_to_leader),
4278 M_FILEDESC_TO_LEADER, M_WAITOK);
4279 fdtol->fdl_refcount = 1;
4280 fdtol->fdl_holdcount = 0;
4281 fdtol->fdl_wakeup = 0;
4282 fdtol->fdl_leader = leader;
4284 FILEDESC_XLOCK(fdp);
4285 fdtol->fdl_next = old->fdl_next;
4286 fdtol->fdl_prev = old;
4287 old->fdl_next = fdtol;
4288 fdtol->fdl_next->fdl_prev = fdtol;
4289 FILEDESC_XUNLOCK(fdp);
4291 fdtol->fdl_next = fdtol;
4292 fdtol->fdl_prev = fdtol;
4297 struct filedesc_to_leader *
4298 filedesc_to_leader_share(struct filedesc_to_leader *fdtol, struct filedesc *fdp)
4300 FILEDESC_XLOCK(fdp);
4301 fdtol->fdl_refcount++;
4302 FILEDESC_XUNLOCK(fdp);
4307 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4310 struct filedesc *fdp;
4312 int count, off, minoff;
4318 if (*(int *)arg1 != 0)
4321 fdp = curproc->p_fd;
4323 FILEDESC_SLOCK(fdp);
4325 off = NDSLOT(fdp->fd_nfiles - 1);
4326 for (minoff = NDSLOT(0); off >= minoff; --off)
4327 count += bitcountl(map[off]);
4328 FILEDESC_SUNLOCK(fdp);
4330 return (SYSCTL_OUT(req, &count, sizeof(count)));
4333 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4334 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4335 "Number of open file descriptors");
4338 * Get file structures globally.
4341 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4344 struct filedesc *fdp;
4347 int error, n, lastfile;
4349 error = sysctl_wire_old_buffer(req, 0);
4352 if (req->oldptr == NULL) {
4354 sx_slock(&allproc_lock);
4355 FOREACH_PROC_IN_SYSTEM(p) {
4357 if (p->p_state == PRS_NEW) {
4365 /* overestimates sparse tables. */
4366 n += fdp->fd_nfiles;
4369 sx_sunlock(&allproc_lock);
4370 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4373 bzero(&xf, sizeof(xf));
4374 xf.xf_size = sizeof(xf);
4375 sx_slock(&allproc_lock);
4376 FOREACH_PROC_IN_SYSTEM(p) {
4378 if (p->p_state == PRS_NEW) {
4382 if (p_cansee(req->td, p) != 0) {
4386 xf.xf_pid = p->p_pid;
4387 xf.xf_uid = p->p_ucred->cr_uid;
4392 FILEDESC_SLOCK(fdp);
4393 if (refcount_load(&fdp->fd_refcnt) == 0)
4395 lastfile = fdlastfile(fdp);
4396 for (n = 0; refcount_load(&fdp->fd_refcnt) > 0 && n <= lastfile;
4398 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4401 xf.xf_file = (uintptr_t)fp;
4402 xf.xf_data = (uintptr_t)fp->f_data;
4403 xf.xf_vnode = (uintptr_t)fp->f_vnode;
4404 xf.xf_type = (uintptr_t)fp->f_type;
4405 xf.xf_count = refcount_load(&fp->f_count);
4407 xf.xf_offset = foffset_get(fp);
4408 xf.xf_flag = fp->f_flag;
4409 error = SYSCTL_OUT(req, &xf, sizeof(xf));
4412 * There is no need to re-check the fdtable refcount
4413 * here since the filedesc lock is not dropped in the
4420 FILEDESC_SUNLOCK(fdp);
4425 sx_sunlock(&allproc_lock);
4429 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4430 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4432 #ifdef KINFO_FILE_SIZE
4433 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4437 xlate_fflags(int fflags)
4439 static const struct {
4442 } fflags_table[] = {
4443 { FAPPEND, KF_FLAG_APPEND },
4444 { FASYNC, KF_FLAG_ASYNC },
4445 { FFSYNC, KF_FLAG_FSYNC },
4446 { FHASLOCK, KF_FLAG_HASLOCK },
4447 { FNONBLOCK, KF_FLAG_NONBLOCK },
4448 { FREAD, KF_FLAG_READ },
4449 { FWRITE, KF_FLAG_WRITE },
4450 { O_CREAT, KF_FLAG_CREAT },
4451 { O_DIRECT, KF_FLAG_DIRECT },
4452 { O_EXCL, KF_FLAG_EXCL },
4453 { O_EXEC, KF_FLAG_EXEC },
4454 { O_EXLOCK, KF_FLAG_EXLOCK },
4455 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4456 { O_SHLOCK, KF_FLAG_SHLOCK },
4457 { O_TRUNC, KF_FLAG_TRUNC }
4463 for (i = 0; i < nitems(fflags_table); i++)
4464 if (fflags & fflags_table[i].fflag)
4465 kflags |= fflags_table[i].kf_fflag;
4469 /* Trim unused data from kf_path by truncating the structure size. */
4471 pack_kinfo(struct kinfo_file *kif)
4474 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4475 strlen(kif->kf_path) + 1;
4476 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4480 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4481 struct kinfo_file *kif, struct filedesc *fdp, int flags)
4485 bzero(kif, sizeof(*kif));
4487 /* Set a default type to allow for empty fill_kinfo() methods. */
4488 kif->kf_type = KF_TYPE_UNKNOWN;
4489 kif->kf_flags = xlate_fflags(fp->f_flag);
4490 if (rightsp != NULL)
4491 kif->kf_cap_rights = *rightsp;
4493 cap_rights_init_zero(&kif->kf_cap_rights);
4495 kif->kf_ref_count = refcount_load(&fp->f_count);
4496 kif->kf_offset = foffset_get(fp);
4499 * This may drop the filedesc lock, so the 'fp' cannot be
4500 * accessed after this call.
4502 error = fo_fill_kinfo(fp, kif, fdp);
4504 kif->kf_status |= KF_ATTR_VALID;
4505 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4508 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4512 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4513 struct kinfo_file *kif, int flags)
4517 bzero(kif, sizeof(*kif));
4519 kif->kf_type = KF_TYPE_VNODE;
4520 error = vn_fill_kinfo_vnode(vp, kif);
4522 kif->kf_status |= KF_ATTR_VALID;
4523 kif->kf_flags = xlate_fflags(fflags);
4524 cap_rights_init_zero(&kif->kf_cap_rights);
4526 kif->kf_ref_count = -1;
4527 kif->kf_offset = -1;
4528 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4531 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4535 struct export_fd_buf {
4536 struct filedesc *fdp;
4537 struct pwddesc *pdp;
4540 struct kinfo_file kif;
4545 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4547 struct kinfo_file *kif;
4550 if (efbuf->remainder != -1) {
4551 if (efbuf->remainder < kif->kf_structsize)
4553 efbuf->remainder -= kif->kf_structsize;
4555 if (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) != 0)
4556 return (sbuf_error(efbuf->sb));
4561 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4562 struct export_fd_buf *efbuf)
4566 if (efbuf->remainder == 0)
4568 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4570 FILEDESC_SUNLOCK(efbuf->fdp);
4571 error = export_kinfo_to_sb(efbuf);
4572 FILEDESC_SLOCK(efbuf->fdp);
4577 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4578 struct export_fd_buf *efbuf)
4582 if (efbuf->remainder == 0)
4584 if (efbuf->pdp != NULL)
4585 PWDDESC_XUNLOCK(efbuf->pdp);
4586 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4587 error = export_kinfo_to_sb(efbuf);
4588 if (efbuf->pdp != NULL)
4589 PWDDESC_XLOCK(efbuf->pdp);
4594 * Store a process file descriptor information to sbuf.
4596 * Takes a locked proc as argument, and returns with the proc unlocked.
4599 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
4603 struct filedesc *fdp;
4604 struct pwddesc *pdp;
4605 struct export_fd_buf *efbuf;
4606 struct vnode *cttyvp, *textvp, *tracevp;
4608 int error, i, lastfile;
4609 cap_rights_t rights;
4611 PROC_LOCK_ASSERT(p, MA_OWNED);
4614 tracevp = ktr_get_tracevp(p, true);
4616 textvp = p->p_textvp;
4619 /* Controlling tty. */
4621 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4622 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4630 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4634 efbuf->remainder = maxlen;
4635 efbuf->flags = flags;
4638 if (tracevp != NULL)
4639 error = export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE,
4640 FREAD | FWRITE, efbuf);
4641 if (error == 0 && textvp != NULL)
4642 error = export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD,
4644 if (error == 0 && cttyvp != NULL)
4645 error = export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY,
4646 FREAD | FWRITE, efbuf);
4647 if (error != 0 || pdp == NULL || fdp == NULL)
4652 pwd = pwd_hold_pwddesc(pdp);
4654 /* working directory */
4655 if (pwd->pwd_cdir != NULL) {
4656 vrefact(pwd->pwd_cdir);
4657 error = export_vnode_to_sb(pwd->pwd_cdir,
4658 KF_FD_TYPE_CWD, FREAD, efbuf);
4660 /* root directory */
4661 if (error == 0 && pwd->pwd_rdir != NULL) {
4662 vrefact(pwd->pwd_rdir);
4663 error = export_vnode_to_sb(pwd->pwd_rdir,
4664 KF_FD_TYPE_ROOT, FREAD, efbuf);
4666 /* jail directory */
4667 if (error == 0 && pwd->pwd_jdir != NULL) {
4668 vrefact(pwd->pwd_jdir);
4669 error = export_vnode_to_sb(pwd->pwd_jdir,
4670 KF_FD_TYPE_JAIL, FREAD, efbuf);
4673 PWDDESC_XUNLOCK(pdp);
4678 FILEDESC_SLOCK(fdp);
4679 if (refcount_load(&fdp->fd_refcnt) == 0)
4681 lastfile = fdlastfile(fdp);
4682 for (i = 0; i <= lastfile; i++) {
4683 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4686 rights = *cap_rights(fdp, i);
4687 #else /* !CAPABILITIES */
4688 rights = cap_no_rights;
4691 * Create sysctl entry. It is OK to drop the filedesc
4692 * lock inside of export_file_to_sb() as we will
4693 * re-validate and re-evaluate its properties when the
4696 error = export_file_to_sb(fp, i, &rights, efbuf);
4697 if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4701 FILEDESC_SUNLOCK(fdp);
4707 free(efbuf, M_TEMP);
4711 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
4714 * Get per-process file descriptors for use by procstat(1), et al.
4717 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4723 int error, error2, *name;
4731 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4732 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4733 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4738 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4739 error = kern_proc_filedesc_out(p, &sb, maxlen,
4740 KERN_FILEDESC_PACK_KINFO);
4741 error2 = sbuf_finish(&sb);
4743 return (error != 0 ? error : error2);
4746 #ifdef COMPAT_FREEBSD7
4747 #ifdef KINFO_OFILE_SIZE
4748 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4752 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4755 okif->kf_structsize = sizeof(*okif);
4756 okif->kf_type = kif->kf_type;
4757 okif->kf_fd = kif->kf_fd;
4758 okif->kf_ref_count = kif->kf_ref_count;
4759 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4760 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4761 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4762 okif->kf_offset = kif->kf_offset;
4763 if (kif->kf_type == KF_TYPE_VNODE)
4764 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4766 okif->kf_vnode_type = KF_VTYPE_VNON;
4767 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4768 if (kif->kf_type == KF_TYPE_SOCKET) {
4769 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4770 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4771 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4772 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4773 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4775 okif->kf_sa_local.ss_family = AF_UNSPEC;
4776 okif->kf_sa_peer.ss_family = AF_UNSPEC;
4781 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4782 struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4787 PWDDESC_XUNLOCK(pdp);
4788 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4789 kinfo_to_okinfo(kif, okif);
4790 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4796 * Get per-process file descriptors for use by procstat(1), et al.
4799 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4801 struct kinfo_ofile *okif;
4802 struct kinfo_file *kif;
4803 struct filedesc *fdp;
4804 struct pwddesc *pdp;
4807 int error, i, lastfile, *name;
4816 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4823 if (fdp == NULL || pdp == NULL) {
4828 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4829 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4831 pwd = pwd_hold_pwddesc(pdp);
4833 if (pwd->pwd_cdir != NULL)
4834 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4836 if (pwd->pwd_rdir != NULL)
4837 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4839 if (pwd->pwd_jdir != NULL)
4840 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4843 PWDDESC_XUNLOCK(pdp);
4846 FILEDESC_SLOCK(fdp);
4847 if (refcount_load(&fdp->fd_refcnt) == 0)
4849 lastfile = fdlastfile(fdp);
4850 for (i = 0; i <= lastfile; i++) {
4851 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4853 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4854 KERN_FILEDESC_PACK_KINFO);
4855 FILEDESC_SUNLOCK(fdp);
4856 kinfo_to_okinfo(kif, okif);
4857 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4858 FILEDESC_SLOCK(fdp);
4859 if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4863 FILEDESC_SUNLOCK(fdp);
4871 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4872 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4873 "Process ofiledesc entries");
4874 #endif /* COMPAT_FREEBSD7 */
4877 vntype_to_kinfo(int vtype)
4882 } vtypes_table[] = {
4883 { VBAD, KF_VTYPE_VBAD },
4884 { VBLK, KF_VTYPE_VBLK },
4885 { VCHR, KF_VTYPE_VCHR },
4886 { VDIR, KF_VTYPE_VDIR },
4887 { VFIFO, KF_VTYPE_VFIFO },
4888 { VLNK, KF_VTYPE_VLNK },
4889 { VNON, KF_VTYPE_VNON },
4890 { VREG, KF_VTYPE_VREG },
4891 { VSOCK, KF_VTYPE_VSOCK }
4896 * Perform vtype translation.
4898 for (i = 0; i < nitems(vtypes_table); i++)
4899 if (vtypes_table[i].vtype == vtype)
4900 return (vtypes_table[i].kf_vtype);
4902 return (KF_VTYPE_UNKNOWN);
4905 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4906 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4907 "Process filedesc entries");
4910 * Store a process current working directory information to sbuf.
4912 * Takes a locked proc as argument, and returns with the proc unlocked.
4915 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4917 struct pwddesc *pdp;
4919 struct export_fd_buf *efbuf;
4923 PROC_LOCK_ASSERT(p, MA_OWNED);
4930 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4934 efbuf->remainder = maxlen;
4938 pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4939 cdir = pwd->pwd_cdir;
4944 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4946 PWDDESC_XUNLOCK(pdp);
4948 free(efbuf, M_TEMP);
4953 * Get per-process current working directory.
4956 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4962 int error, error2, *name;
4970 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4971 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4972 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4977 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4978 error = kern_proc_cwd_out(p, &sb, maxlen);
4979 error2 = sbuf_finish(&sb);
4981 return (error != 0 ? error : error2);
4984 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4985 sysctl_kern_proc_cwd, "Process current working directory");
4989 * For the purposes of debugging, generate a human-readable string for the
4993 file_type_to_name(short type)
5021 case DTYPE_PROCDESC:
5025 case DTYPE_LINUXTFD:
5033 * For the purposes of debugging, identify a process (if any, perhaps one of
5034 * many) that references the passed file in its file descriptor array. Return
5037 static struct proc *
5038 file_to_first_proc(struct file *fp)
5040 struct filedesc *fdp;
5044 FOREACH_PROC_IN_SYSTEM(p) {
5045 if (p->p_state == PRS_NEW)
5050 for (n = 0; n < fdp->fd_nfiles; n++) {
5051 if (fp == fdp->fd_ofiles[n].fde_file)
5059 db_print_file(struct file *fp, int header)
5061 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
5065 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
5066 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
5067 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
5069 p = file_to_first_proc(fp);
5070 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
5071 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
5072 fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
5073 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
5078 DB_SHOW_COMMAND(file, db_show_file)
5083 db_printf("usage: show file <addr>\n");
5086 fp = (struct file *)addr;
5087 db_print_file(fp, 1);
5090 DB_SHOW_COMMAND(files, db_show_files)
5092 struct filedesc *fdp;
5099 FOREACH_PROC_IN_SYSTEM(p) {
5100 if (p->p_state == PRS_NEW)
5102 if ((fdp = p->p_fd) == NULL)
5104 for (n = 0; n < fdp->fd_nfiles; ++n) {
5105 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
5107 db_print_file(fp, header);
5114 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
5115 CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5116 &maxfilesperproc, 0, "Maximum files allowed open per process");
5118 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5119 &maxfiles, 0, "Maximum number of files");
5121 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
5122 &openfiles, 0, "System-wide number of open files");
5126 filelistinit(void *dummy)
5129 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
5130 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
5131 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
5132 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5133 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
5134 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
5136 * XXXMJG this is a temporary hack due to boot ordering issues against
5139 vfs_smr = uma_zone_get_smr(pwd_zone);
5140 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
5142 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
5144 /*-------------------------------------------------------------------*/
5147 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
5148 int flags, struct thread *td)
5155 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5163 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
5171 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
5179 badfo_kqfilter(struct file *fp, struct knote *kn)
5186 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
5194 badfo_close(struct file *fp, struct thread *td)
5201 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5209 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5217 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5218 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5226 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
5232 struct fileops badfileops = {
5233 .fo_read = badfo_readwrite,
5234 .fo_write = badfo_readwrite,
5235 .fo_truncate = badfo_truncate,
5236 .fo_ioctl = badfo_ioctl,
5237 .fo_poll = badfo_poll,
5238 .fo_kqfilter = badfo_kqfilter,
5239 .fo_stat = badfo_stat,
5240 .fo_close = badfo_close,
5241 .fo_chmod = badfo_chmod,
5242 .fo_chown = badfo_chown,
5243 .fo_sendfile = badfo_sendfile,
5244 .fo_fill_kinfo = badfo_fill_kinfo,
5248 path_poll(struct file *fp, int events, struct ucred *active_cred,
5255 path_close(struct file *fp, struct thread *td)
5257 MPASS(fp->f_type == DTYPE_VNODE);
5258 fp->f_ops = &badfileops;
5263 struct fileops path_fileops = {
5264 .fo_read = badfo_readwrite,
5265 .fo_write = badfo_readwrite,
5266 .fo_truncate = badfo_truncate,
5267 .fo_ioctl = badfo_ioctl,
5268 .fo_poll = path_poll,
5269 .fo_kqfilter = vn_kqfilter_opath,
5270 .fo_stat = vn_statfile,
5271 .fo_close = path_close,
5272 .fo_chmod = badfo_chmod,
5273 .fo_chown = badfo_chown,
5274 .fo_sendfile = badfo_sendfile,
5275 .fo_fill_kinfo = vn_fill_kinfo,
5276 .fo_flags = DFLAG_PASSABLE,
5280 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
5281 int flags, struct thread *td)
5284 return (EOPNOTSUPP);
5288 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5296 invfo_ioctl(struct file *fp, u_long com, void *data,
5297 struct ucred *active_cred, struct thread *td)
5304 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
5308 return (poll_no_poll(events));
5312 invfo_kqfilter(struct file *fp, struct knote *kn)
5319 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5327 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5335 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5336 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5343 /*-------------------------------------------------------------------*/
5346 * File Descriptor pseudo-device driver (/dev/fd/).
5348 * Opening minor device N dup()s the file (if any) connected to file
5349 * descriptor N belonging to the calling process. Note that this driver
5350 * consists of only the ``open()'' routine, because all subsequent
5351 * references to this file will be direct to the other driver.
5353 * XXX: we could give this one a cloning event handler if necessary.
5358 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5362 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5363 * the file descriptor being sought for duplication. The error
5364 * return ensures that the vnode for this device will be released
5365 * by vn_open. Open will detect this special error and take the
5366 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5367 * will simply report the error.
5369 td->td_dupfd = dev2unit(dev);
5373 static struct cdevsw fildesc_cdevsw = {
5374 .d_version = D_VERSION,
5380 fildesc_drvinit(void *unused)
5384 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5385 UID_ROOT, GID_WHEEL, 0666, "fd/0");
5386 make_dev_alias(dev, "stdin");
5387 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5388 UID_ROOT, GID_WHEEL, 0666, "fd/1");
5389 make_dev_alias(dev, "stdout");
5390 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5391 UID_ROOT, GID_WHEEL, 0666, "fd/2");
5392 make_dev_alias(dev, "stderr");
5395 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);