2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_capsicum.h"
44 #include "opt_ktrace.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capsicum.h>
51 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
56 #include <sys/kernel.h>
57 #include <sys/limits.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/selinfo.h>
66 #include <sys/protosw.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
70 #include <sys/signalvar.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysctl.h>
77 #include <sys/sysproto.h>
78 #include <sys/unistd.h>
80 #include <sys/vnode.h>
82 #include <sys/ktrace.h>
87 #include <security/audit/audit.h>
94 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
95 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
96 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
97 "file desc to leader structures");
98 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
99 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
101 MALLOC_DECLARE(M_FADVISE);
103 static __read_mostly uma_zone_t file_zone;
104 static __read_mostly uma_zone_t filedesc0_zone;
105 static __read_mostly uma_zone_t pwd_zone;
106 static __read_mostly smr_t pwd_smr;
108 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
109 struct thread *td, int holdleaders);
110 static int fd_first_free(struct filedesc *fdp, int low, int size);
111 static int fd_last_used(struct filedesc *fdp, int size);
112 static void fdgrowtable(struct filedesc *fdp, int nfd);
113 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
114 static void fdunused(struct filedesc *fdp, int fd);
115 static void fdused(struct filedesc *fdp, int fd);
116 static int getmaxfd(struct thread *td);
117 static u_long *filecaps_copy_prep(const struct filecaps *src);
118 static void filecaps_copy_finish(const struct filecaps *src,
119 struct filecaps *dst, u_long *ioctls);
120 static u_long *filecaps_free_prep(struct filecaps *fcaps);
121 static void filecaps_free_finish(u_long *ioctls);
123 static struct pwd *pwd_alloc(void);
128 * - An array of open file descriptors (fd_ofiles)
129 * - An array of file flags (fd_ofileflags)
130 * - A bitmap recording which descriptors are in use (fd_map)
132 * A process starts out with NDFILE descriptors. The value of NDFILE has
133 * been selected based the historical limit of 20 open files, and an
134 * assumption that the majority of processes, especially short-lived
135 * processes like shells, will never need more.
137 * If this initial allocation is exhausted, a larger descriptor table and
138 * map are allocated dynamically, and the pointers in the process's struct
139 * filedesc are updated to point to those. This is repeated every time
140 * the process runs out of file descriptors (provided it hasn't hit its
143 * Since threads may hold references to individual descriptor table
144 * entries, the tables are never freed. Instead, they are placed on a
145 * linked list and freed only when the struct filedesc is released.
148 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
149 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
150 #define NDSLOT(x) ((x) / NDENTRIES)
151 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
152 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
155 * SLIST entry used to keep track of ofiles which must be reclaimed when
159 struct fdescenttbl *ft_table;
160 SLIST_ENTRY(freetable) ft_next;
164 * Initial allocation: a filedesc structure + the head of SLIST used to
165 * keep track of old ofiles + enough space for NDFILE descriptors.
168 struct fdescenttbl0 {
170 struct filedescent fdt_ofiles[NDFILE];
174 struct filedesc fd_fd;
175 SLIST_HEAD(, freetable) fd_free;
176 struct fdescenttbl0 fd_dfiles;
177 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
181 * Descriptor management.
183 static int __exclusive_cache_line openfiles; /* actual number of open files */
184 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
185 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
188 * If low >= size, just return low. Otherwise find the first zero bit in the
189 * given bitmap, starting at low and not exceeding size - 1. Return size if
193 fd_first_free(struct filedesc *fdp, int low, int size)
195 NDSLOTTYPE *map = fdp->fd_map;
203 if (low % NDENTRIES) {
204 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
205 if ((mask &= ~map[off]) != 0UL)
206 return (off * NDENTRIES + ffsl(mask) - 1);
209 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
210 if (map[off] != ~0UL)
211 return (off * NDENTRIES + ffsl(~map[off]) - 1);
216 * Find the highest non-zero bit in the given bitmap, starting at 0 and
217 * not exceeding size - 1. Return -1 if not found.
220 fd_last_used(struct filedesc *fdp, int size)
222 NDSLOTTYPE *map = fdp->fd_map;
227 if (size % NDENTRIES) {
228 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
229 if ((mask &= map[off]) != 0)
230 return (off * NDENTRIES + flsl(mask) - 1);
233 for (minoff = NDSLOT(0); off >= minoff; --off)
235 return (off * NDENTRIES + flsl(map[off]) - 1);
240 fdisused(struct filedesc *fdp, int fd)
243 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
244 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
246 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
250 * Mark a file descriptor as used.
253 fdused_init(struct filedesc *fdp, int fd)
256 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
258 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
262 fdused(struct filedesc *fdp, int fd)
265 FILEDESC_XLOCK_ASSERT(fdp);
267 fdused_init(fdp, fd);
268 if (fd > fdp->fd_lastfile)
269 fdp->fd_lastfile = fd;
270 if (fd == fdp->fd_freefile)
275 * Mark a file descriptor as unused.
278 fdunused(struct filedesc *fdp, int fd)
281 FILEDESC_XLOCK_ASSERT(fdp);
283 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
284 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
285 ("fd=%d is still in use", fd));
287 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288 if (fd < fdp->fd_freefile)
289 fdp->fd_freefile = fd;
290 if (fd == fdp->fd_lastfile)
291 fdp->fd_lastfile = fd_last_used(fdp, fd);
295 * Free a file descriptor.
297 * Avoid some work if fdp is about to be destroyed.
300 fdefree_last(struct filedescent *fde)
303 filecaps_free(&fde->fde_caps);
307 fdfree(struct filedesc *fdp, int fd)
309 struct filedescent *fde;
311 fde = &fdp->fd_ofiles[fd];
313 seqc_write_begin(&fde->fde_seqc);
315 fde->fde_file = NULL;
317 seqc_write_end(&fde->fde_seqc);
324 * System calls on descriptors.
326 #ifndef _SYS_SYSPROTO_H_
327 struct getdtablesize_args {
333 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
339 td->td_retval[0] = getmaxfd(td);
341 PROC_LOCK(td->td_proc);
342 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
343 PROC_UNLOCK(td->td_proc);
344 if (lim < td->td_retval[0])
345 td->td_retval[0] = lim;
351 * Duplicate a file descriptor to a particular value.
353 * Note: keep in mind that a potential race condition exists when closing
354 * descriptors from a shared descriptor table (via rfork).
356 #ifndef _SYS_SYSPROTO_H_
364 sys_dup2(struct thread *td, struct dup2_args *uap)
367 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
371 * Duplicate a file descriptor.
373 #ifndef _SYS_SYSPROTO_H_
380 sys_dup(struct thread *td, struct dup_args *uap)
383 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
387 * The file control system call.
389 #ifndef _SYS_SYSPROTO_H_
398 sys_fcntl(struct thread *td, struct fcntl_args *uap)
401 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
405 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
419 * Convert old flock structure to new.
421 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
422 fl.l_start = ofl.l_start;
423 fl.l_len = ofl.l_len;
424 fl.l_pid = ofl.l_pid;
425 fl.l_type = ofl.l_type;
426 fl.l_whence = ofl.l_whence;
440 arg1 = (intptr_t)&fl;
446 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
447 arg1 = (intptr_t)&fl;
455 error = kern_fcntl(td, fd, newcmd, arg1);
458 if (cmd == F_OGETLK) {
459 ofl.l_start = fl.l_start;
460 ofl.l_len = fl.l_len;
461 ofl.l_pid = fl.l_pid;
462 ofl.l_type = fl.l_type;
463 ofl.l_whence = fl.l_whence;
464 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
465 } else if (cmd == F_GETLK) {
466 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
472 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
474 struct filedesc *fdp;
476 struct file *fp, *fp2;
477 struct filedescent *fde;
481 int error, flg, seals, tmp;
495 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
498 case F_DUPFD_CLOEXEC:
500 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
505 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
508 case F_DUP2FD_CLOEXEC:
510 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
516 fde = fdeget_locked(fdp, fd);
519 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
522 FILEDESC_SUNLOCK(fdp);
528 fde = fdeget_locked(fdp, fd);
530 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
531 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
534 FILEDESC_XUNLOCK(fdp);
538 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
541 td->td_retval[0] = OFLAGS(fp->f_flag);
546 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
550 tmp = flg = fp->f_flag;
552 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
553 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
554 tmp = fp->f_flag & FNONBLOCK;
555 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
560 tmp = fp->f_flag & FASYNC;
561 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
566 atomic_clear_int(&fp->f_flag, FNONBLOCK);
568 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
573 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
576 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
578 td->td_retval[0] = tmp;
583 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
587 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
592 error = priv_check(td, PRIV_NFS_LOCKD);
600 /* FALLTHROUGH F_SETLK */
604 flp = (struct flock *)arg;
605 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
610 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
613 if (fp->f_type != DTYPE_VNODE) {
619 if (flp->l_whence == SEEK_CUR) {
620 foffset = foffset_get(fp);
623 foffset > OFF_MAX - flp->l_start)) {
628 flp->l_start += foffset;
632 switch (flp->l_type) {
634 if ((fp->f_flag & FREAD) == 0) {
638 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
639 PROC_LOCK(p->p_leader);
640 p->p_leader->p_flag |= P_ADVLOCK;
641 PROC_UNLOCK(p->p_leader);
643 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
647 if ((fp->f_flag & FWRITE) == 0) {
651 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
652 PROC_LOCK(p->p_leader);
653 p->p_leader->p_flag |= P_ADVLOCK;
654 PROC_UNLOCK(p->p_leader);
656 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
664 if (flg != F_REMOTE) {
668 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
669 F_UNLCKSYS, flp, flg);
675 if (error != 0 || flp->l_type == F_UNLCK ||
676 flp->l_type == F_UNLCKSYS) {
682 * Check for a race with close.
684 * The vnode is now advisory locked (or unlocked, but this case
685 * is not really important) as the caller requested.
686 * We had to drop the filedesc lock, so we need to recheck if
687 * the descriptor is still valid, because if it was closed
688 * in the meantime we need to remove advisory lock from the
689 * vnode - close on any descriptor leading to an advisory
690 * locked vnode, removes that lock.
691 * We will return 0 on purpose in that case, as the result of
692 * successful advisory lock might have been externally visible
693 * already. This is fine - effectively we pretend to the caller
694 * that the closing thread was a bit slower and that the
695 * advisory lock succeeded before the close.
697 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
703 flp->l_whence = SEEK_SET;
706 flp->l_type = F_UNLCK;
707 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708 F_UNLCK, flp, F_POSIX);
715 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
718 if (fp->f_type != DTYPE_VNODE) {
723 flp = (struct flock *)arg;
724 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
725 flp->l_type != F_UNLCK) {
730 if (flp->l_whence == SEEK_CUR) {
731 foffset = foffset_get(fp);
732 if ((flp->l_start > 0 &&
733 foffset > OFF_MAX - flp->l_start) ||
735 foffset < OFF_MIN - flp->l_start)) {
740 flp->l_start += foffset;
743 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
749 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
752 error = fo_add_seals(fp, arg);
757 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
760 if (fo_get_seals(fp, &seals) == 0)
761 td->td_retval[0] = seals;
768 arg = arg ? 128 * 1024: 0;
771 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
774 if (fp->f_type != DTYPE_VNODE) {
780 if (vp->v_type != VREG) {
787 * Exclusive lock synchronizes against f_seqcount reads and
788 * writes in sequential_heuristic().
790 error = vn_lock(vp, LK_EXCLUSIVE);
796 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
797 arg = MIN(arg, INT_MAX - bsize + 1);
798 fp->f_seqcount = MIN(IO_SEQMAX,
799 (arg + bsize - 1) / bsize);
800 atomic_set_int(&fp->f_flag, FRDAHEAD);
802 atomic_clear_int(&fp->f_flag, FRDAHEAD);
810 * Check if the vnode is part of a union stack (either the
811 * "union" flag from mount(2) or unionfs).
813 * Prior to introduction of this op libc's readdir would call
814 * fstatfs(2), in effect unnecessarily copying kilobytes of
815 * data just to check fs name and a mount flag.
817 * Fixing the code to handle everything in the kernel instead
818 * is a non-trivial endeavor and has low priority, thus this
819 * horrible kludge facilitates the current behavior in a much
820 * cheaper manner until someone(tm) sorts this out.
822 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
825 if (fp->f_type != DTYPE_VNODE) {
832 * Since we don't prevent dooming the vnode even non-null mp
833 * found can become immediately stale. This is tolerable since
834 * mount points are type-stable (providing safe memory access)
835 * and any vfs op on this vnode going forward will return an
836 * error (meaning return value in this case is meaningless).
838 mp = atomic_load_ptr(&vp->v_mount);
839 if (__predict_false(mp == NULL)) {
844 td->td_retval[0] = 0;
845 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
846 mp->mnt_flag & MNT_UNION)
847 td->td_retval[0] = 1;
859 getmaxfd(struct thread *td)
862 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
866 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
869 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
871 struct filedesc *fdp;
872 struct filedescent *oldfde, *newfde;
875 u_long *oioctls, *nioctls;
882 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
883 MPASS(mode < FDDUP_LASTMODE);
886 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
889 * Verify we have a valid descriptor to dup from and possibly to
890 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
891 * return EINVAL when the new descriptor is out of bounds.
896 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
897 maxfd = getmaxfd(td);
899 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
903 if (fget_locked(fdp, old) == NULL)
905 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
906 td->td_retval[0] = new;
907 if (flags & FDDUP_FLAG_CLOEXEC)
908 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
913 oldfde = &fdp->fd_ofiles[old];
914 if (!fhold(oldfde->fde_file))
918 * If the caller specified a file descriptor, make sure the file
919 * table is large enough to hold it, and grab it. Otherwise, just
920 * allocate a new descriptor the usual way.
925 if ((error = fdalloc(td, new, &new)) != 0) {
926 fdrop(oldfde->fde_file, td);
930 case FDDUP_MUSTREPLACE:
931 /* Target file descriptor must exist. */
932 if (fget_locked(fdp, new) == NULL) {
933 fdrop(oldfde->fde_file, td);
938 if (new >= fdp->fd_nfiles) {
940 * The resource limits are here instead of e.g.
941 * fdalloc(), because the file descriptor table may be
942 * shared between processes, so we can't really use
943 * racct_add()/racct_sub(). Instead of counting the
944 * number of actually allocated descriptors, just put
945 * the limit on the size of the file descriptor table.
948 if (RACCT_ENABLED()) {
949 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
952 fdrop(oldfde->fde_file, td);
957 fdgrowtable_exp(fdp, new + 1);
959 if (!fdisused(fdp, new))
963 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
966 KASSERT(old != new, ("new fd is same as old"));
968 newfde = &fdp->fd_ofiles[new];
969 delfp = newfde->fde_file;
971 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
974 * Duplicate the source descriptor.
977 seqc_write_begin(&newfde->fde_seqc);
979 oioctls = filecaps_free_prep(&newfde->fde_caps);
980 memcpy(newfde, oldfde, fde_change_size);
981 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
983 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
984 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
986 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
988 seqc_write_end(&newfde->fde_seqc);
990 td->td_retval[0] = new;
995 (void) closefp(fdp, new, delfp, td, 1);
996 FILEDESC_UNLOCK_ASSERT(fdp);
999 FILEDESC_XUNLOCK(fdp);
1002 filecaps_free_finish(oioctls);
1007 * If sigio is on the list associated with a process or process group,
1008 * disable signalling from the device, remove sigio from the list and
1012 funsetown(struct sigio **sigiop)
1014 struct sigio *sigio;
1016 if (*sigiop == NULL)
1020 if (sigio == NULL) {
1024 *(sigio->sio_myref) = NULL;
1025 if ((sigio)->sio_pgid < 0) {
1026 struct pgrp *pg = (sigio)->sio_pgrp;
1028 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1029 sigio, sio_pgsigio);
1032 struct proc *p = (sigio)->sio_proc;
1034 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1035 sigio, sio_pgsigio);
1039 crfree(sigio->sio_ucred);
1040 free(sigio, M_SIGIO);
1044 * Free a list of sigio structures.
1045 * We only need to lock the SIGIO_LOCK because we have made ourselves
1046 * inaccessible to callers of fsetown and therefore do not need to lock
1047 * the proc or pgrp struct for the list manipulation.
1050 funsetownlst(struct sigiolst *sigiolst)
1054 struct sigio *sigio;
1056 sigio = SLIST_FIRST(sigiolst);
1063 * Every entry of the list should belong
1064 * to a single proc or pgrp.
1066 if (sigio->sio_pgid < 0) {
1067 pg = sigio->sio_pgrp;
1068 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1069 } else /* if (sigio->sio_pgid > 0) */ {
1070 p = sigio->sio_proc;
1071 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1075 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1076 *(sigio->sio_myref) = NULL;
1078 KASSERT(sigio->sio_pgid < 0,
1079 ("Proc sigio in pgrp sigio list"));
1080 KASSERT(sigio->sio_pgrp == pg,
1081 ("Bogus pgrp in sigio list"));
1083 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1086 } else /* if (p != NULL) */ {
1087 KASSERT(sigio->sio_pgid > 0,
1088 ("Pgrp sigio in proc sigio list"));
1089 KASSERT(sigio->sio_proc == p,
1090 ("Bogus proc in sigio list"));
1092 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1097 crfree(sigio->sio_ucred);
1098 free(sigio, M_SIGIO);
1105 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1107 * After permission checking, add a sigio structure to the sigio list for
1108 * the process or process group.
1111 fsetown(pid_t pgid, struct sigio **sigiop)
1115 struct sigio *sigio;
1125 /* Allocate and fill in the new sigio out of locks. */
1126 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1127 sigio->sio_pgid = pgid;
1128 sigio->sio_ucred = crhold(curthread->td_ucred);
1129 sigio->sio_myref = sigiop;
1131 sx_slock(&proctree_lock);
1140 * Policy - Don't allow a process to FSETOWN a process
1141 * in another session.
1143 * Remove this test to allow maximum flexibility or
1144 * restrict FSETOWN to the current process or process
1145 * group for maximum safety.
1148 if (proc->p_session != curthread->td_proc->p_session) {
1154 } else /* if (pgid < 0) */ {
1155 pgrp = pgfind(-pgid);
1163 * Policy - Don't allow a process to FSETOWN a process
1164 * in another session.
1166 * Remove this test to allow maximum flexibility or
1167 * restrict FSETOWN to the current process or process
1168 * group for maximum safety.
1170 if (pgrp->pg_session != curthread->td_proc->p_session) {
1181 * Since funsetownlst() is called without the proctree
1182 * locked, we need to check for P_WEXIT.
1183 * XXX: is ESRCH correct?
1185 if ((proc->p_flag & P_WEXIT) != 0) {
1190 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1191 sigio->sio_proc = proc;
1195 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1196 sigio->sio_pgrp = pgrp;
1199 sx_sunlock(&proctree_lock);
1206 sx_sunlock(&proctree_lock);
1207 crfree(sigio->sio_ucred);
1208 free(sigio, M_SIGIO);
1213 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1216 fgetown(struct sigio **sigiop)
1221 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1227 * Function drops the filedesc lock on return.
1230 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1235 FILEDESC_XLOCK_ASSERT(fdp);
1238 if (td->td_proc->p_fdtol != NULL) {
1240 * Ask fdfree() to sleep to ensure that all relevant
1241 * process leaders can be traversed in closef().
1243 fdp->fd_holdleaderscount++;
1250 * We now hold the fp reference that used to be owned by the
1251 * descriptor array. We have to unlock the FILEDESC *AFTER*
1252 * knote_fdclose to prevent a race of the fd getting opened, a knote
1253 * added, and deleteing a knote for the new fd.
1255 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1256 knote_fdclose(td, fd);
1259 * We need to notify mqueue if the object is of type mqueue.
1261 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1262 mq_fdclose(td, fd, fp);
1263 FILEDESC_XUNLOCK(fdp);
1265 error = closef(fp, td);
1267 FILEDESC_XLOCK(fdp);
1268 fdp->fd_holdleaderscount--;
1269 if (fdp->fd_holdleaderscount == 0 &&
1270 fdp->fd_holdleaderswakeup != 0) {
1271 fdp->fd_holdleaderswakeup = 0;
1272 wakeup(&fdp->fd_holdleaderscount);
1274 FILEDESC_XUNLOCK(fdp);
1280 * Close a file descriptor.
1282 #ifndef _SYS_SYSPROTO_H_
1289 sys_close(struct thread *td, struct close_args *uap)
1292 return (kern_close(td, uap->fd));
1296 kern_close(struct thread *td, int fd)
1298 struct filedesc *fdp;
1301 fdp = td->td_proc->p_fd;
1303 AUDIT_SYSCLOSE(td, fd);
1305 FILEDESC_XLOCK(fdp);
1306 if ((fp = fget_locked(fdp, fd)) == NULL) {
1307 FILEDESC_XUNLOCK(fdp);
1312 /* closefp() drops the FILEDESC lock for us. */
1313 return (closefp(fdp, fd, fp, td, 1));
1317 * Close open file descriptors.
1319 #ifndef _SYS_SYSPROTO_H_
1320 struct closefrom_args {
1326 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1328 struct filedesc *fdp;
1331 fdp = td->td_proc->p_fd;
1332 AUDIT_ARG_FD(uap->lowfd);
1335 * Treat negative starting file descriptor values identical to
1336 * closefrom(0) which closes all files.
1340 FILEDESC_SLOCK(fdp);
1341 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1342 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1343 FILEDESC_SUNLOCK(fdp);
1344 (void)kern_close(td, fd);
1345 FILEDESC_SLOCK(fdp);
1348 FILEDESC_SUNLOCK(fdp);
1352 #if defined(COMPAT_43)
1354 * Return status information about a file descriptor.
1356 #ifndef _SYS_SYSPROTO_H_
1357 struct ofstat_args {
1364 ofstat(struct thread *td, struct ofstat_args *uap)
1370 error = kern_fstat(td, uap->fd, &ub);
1373 error = copyout(&oub, uap->sb, sizeof(oub));
1377 #endif /* COMPAT_43 */
1379 #if defined(COMPAT_FREEBSD11)
1381 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1384 struct freebsd11_stat osb;
1387 error = kern_fstat(td, uap->fd, &sb);
1390 error = freebsd11_cvtstat(&sb, &osb);
1392 error = copyout(&osb, uap->sb, sizeof(osb));
1395 #endif /* COMPAT_FREEBSD11 */
1398 * Return status information about a file descriptor.
1400 #ifndef _SYS_SYSPROTO_H_
1408 sys_fstat(struct thread *td, struct fstat_args *uap)
1413 error = kern_fstat(td, uap->fd, &ub);
1415 error = copyout(&ub, uap->sb, sizeof(ub));
1420 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1427 error = fget(td, fd, &cap_fstat_rights, &fp);
1428 if (__predict_false(error != 0))
1431 AUDIT_ARG_FILE(td->td_proc, fp);
1433 error = fo_stat(fp, sbp, td->td_ucred, td);
1435 #ifdef __STAT_TIME_T_EXT
1436 sbp->st_atim_ext = 0;
1437 sbp->st_mtim_ext = 0;
1438 sbp->st_ctim_ext = 0;
1439 sbp->st_btim_ext = 0;
1442 if (KTRPOINT(td, KTR_STRUCT))
1443 ktrstat_error(sbp, error);
1448 #if defined(COMPAT_FREEBSD11)
1450 * Return status information about a file descriptor.
1452 #ifndef _SYS_SYSPROTO_H_
1453 struct freebsd11_nfstat_args {
1460 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1466 error = kern_fstat(td, uap->fd, &ub);
1468 freebsd11_cvtnstat(&ub, &nub);
1469 error = copyout(&nub, uap->sb, sizeof(nub));
1473 #endif /* COMPAT_FREEBSD11 */
1476 * Return pathconf information about a file descriptor.
1478 #ifndef _SYS_SYSPROTO_H_
1479 struct fpathconf_args {
1486 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1491 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1493 td->td_retval[0] = value;
1498 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1504 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1508 if (name == _PC_ASYNC_IO) {
1509 *valuep = _POSIX_ASYNCHRONOUS_IO;
1514 vn_lock(vp, LK_SHARED | LK_RETRY);
1515 error = VOP_PATHCONF(vp, name, valuep);
1517 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1518 if (name != _PC_PIPE_BUF) {
1533 * Copy filecaps structure allocating memory for ioctls array if needed.
1535 * The last parameter indicates whether the fdtable is locked. If it is not and
1536 * ioctls are encountered, copying fails and the caller must lock the table.
1538 * Note that if the table was not locked, the caller has to check the relevant
1539 * sequence counter to determine whether the operation was successful.
1542 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1546 if (src->fc_ioctls != NULL && !locked)
1548 memcpy(dst, src, sizeof(*src));
1549 if (src->fc_ioctls == NULL)
1552 KASSERT(src->fc_nioctls > 0,
1553 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1555 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1556 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1557 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1562 filecaps_copy_prep(const struct filecaps *src)
1567 if (__predict_true(src->fc_ioctls == NULL))
1570 KASSERT(src->fc_nioctls > 0,
1571 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1573 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1574 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1579 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1585 if (__predict_true(src->fc_ioctls == NULL)) {
1586 MPASS(ioctls == NULL);
1590 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1591 dst->fc_ioctls = ioctls;
1592 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1596 * Move filecaps structure to the new place and clear the old place.
1599 filecaps_move(struct filecaps *src, struct filecaps *dst)
1603 bzero(src, sizeof(*src));
1607 * Fill the given filecaps structure with full rights.
1610 filecaps_fill(struct filecaps *fcaps)
1613 CAP_ALL(&fcaps->fc_rights);
1614 fcaps->fc_ioctls = NULL;
1615 fcaps->fc_nioctls = -1;
1616 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1620 * Free memory allocated within filecaps structure.
1623 filecaps_free(struct filecaps *fcaps)
1626 free(fcaps->fc_ioctls, M_FILECAPS);
1627 bzero(fcaps, sizeof(*fcaps));
1631 filecaps_free_prep(struct filecaps *fcaps)
1635 ioctls = fcaps->fc_ioctls;
1636 bzero(fcaps, sizeof(*fcaps));
1641 filecaps_free_finish(u_long *ioctls)
1644 free(ioctls, M_FILECAPS);
1648 * Validate the given filecaps structure.
1651 filecaps_validate(const struct filecaps *fcaps, const char *func)
1654 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1655 ("%s: invalid rights", func));
1656 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1657 ("%s: invalid fcntls", func));
1658 KASSERT(fcaps->fc_fcntls == 0 ||
1659 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1660 ("%s: fcntls without CAP_FCNTL", func));
1661 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1662 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1663 ("%s: invalid ioctls", func));
1664 KASSERT(fcaps->fc_nioctls == 0 ||
1665 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1666 ("%s: ioctls without CAP_IOCTL", func));
1670 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1674 FILEDESC_XLOCK_ASSERT(fdp);
1676 nfd1 = fdp->fd_nfiles * 2;
1679 fdgrowtable(fdp, nfd1);
1683 * Grow the file table to accommodate (at least) nfd descriptors.
1686 fdgrowtable(struct filedesc *fdp, int nfd)
1688 struct filedesc0 *fdp0;
1689 struct freetable *ft;
1690 struct fdescenttbl *ntable;
1691 struct fdescenttbl *otable;
1692 int nnfiles, onfiles;
1693 NDSLOTTYPE *nmap, *omap;
1696 * If lastfile is -1 this struct filedesc was just allocated and we are
1697 * growing it to accommodate for the one we are going to copy from. There
1698 * is no need to have a lock on this one as it's not visible to anyone.
1700 if (fdp->fd_lastfile != -1)
1701 FILEDESC_XLOCK_ASSERT(fdp);
1703 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1705 /* save old values */
1706 onfiles = fdp->fd_nfiles;
1707 otable = fdp->fd_files;
1710 /* compute the size of the new table */
1711 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1712 if (nnfiles <= onfiles)
1713 /* the table is already large enough */
1717 * Allocate a new table. We need enough space for the number of
1718 * entries, file entries themselves and the struct freetable we will use
1719 * when we decommission the table and place it on the freelist.
1720 * We place the struct freetable in the middle so we don't have
1721 * to worry about padding.
1723 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1724 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1725 sizeof(struct freetable),
1726 M_FILEDESC, M_ZERO | M_WAITOK);
1727 /* copy the old data */
1728 ntable->fdt_nfiles = nnfiles;
1729 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1730 onfiles * sizeof(ntable->fdt_ofiles[0]));
1733 * Allocate a new map only if the old is not large enough. It will
1734 * grow at a slower rate than the table as it can map more
1735 * entries than the table can hold.
1737 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1738 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1740 /* copy over the old data and update the pointer */
1741 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1746 * Make sure that ntable is correctly initialized before we replace
1747 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1750 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1753 * Do not free the old file table, as some threads may still
1754 * reference entries within it. Instead, place it on a freelist
1755 * which will be processed when the struct filedesc is released.
1757 * Note that if onfiles == NDFILE, we're dealing with the original
1758 * static allocation contained within (struct filedesc0 *)fdp,
1759 * which must not be freed.
1761 if (onfiles > NDFILE) {
1762 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1763 fdp0 = (struct filedesc0 *)fdp;
1764 ft->ft_table = otable;
1765 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1768 * The map does not have the same possibility of threads still
1769 * holding references to it. So always free it as long as it
1770 * does not reference the original static allocation.
1772 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1773 free(omap, M_FILEDESC);
1777 * Allocate a file descriptor for the process.
1780 fdalloc(struct thread *td, int minfd, int *result)
1782 struct proc *p = td->td_proc;
1783 struct filedesc *fdp = p->p_fd;
1784 int fd, maxfd, allocfd;
1789 FILEDESC_XLOCK_ASSERT(fdp);
1791 if (fdp->fd_freefile > minfd)
1792 minfd = fdp->fd_freefile;
1794 maxfd = getmaxfd(td);
1797 * Search the bitmap for a free descriptor starting at minfd.
1798 * If none is found, grow the file table.
1800 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1803 if (fd >= fdp->fd_nfiles) {
1804 allocfd = min(fd * 2, maxfd);
1806 if (RACCT_ENABLED()) {
1807 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1813 * fd is already equal to first free descriptor >= minfd, so
1814 * we only need to grow the table and we are done.
1816 fdgrowtable_exp(fdp, allocfd);
1820 * Perform some sanity checks, then mark the file descriptor as
1821 * used and return it to the caller.
1823 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1824 ("invalid descriptor %d", fd));
1825 KASSERT(!fdisused(fdp, fd),
1826 ("fd_first_free() returned non-free descriptor"));
1827 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1828 ("file descriptor isn't free"));
1835 * Allocate n file descriptors for the process.
1838 fdallocn(struct thread *td, int minfd, int *fds, int n)
1840 struct proc *p = td->td_proc;
1841 struct filedesc *fdp = p->p_fd;
1844 FILEDESC_XLOCK_ASSERT(fdp);
1846 for (i = 0; i < n; i++)
1847 if (fdalloc(td, 0, &fds[i]) != 0)
1851 for (i--; i >= 0; i--)
1852 fdunused(fdp, fds[i]);
1860 * Create a new open file structure and allocate a file descriptor for the
1861 * process that refers to it. We add one reference to the file for the
1862 * descriptor table and one reference for resultfp. This is to prevent us
1863 * being preempted and the entry in the descriptor table closed after we
1864 * release the FILEDESC lock.
1867 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1868 struct filecaps *fcaps)
1873 error = falloc_noinstall(td, &fp);
1875 return (error); /* no reference held on error */
1877 error = finstall(td, fp, &fd, flags, fcaps);
1879 fdrop(fp, td); /* one reference (fp only) */
1883 if (resultfp != NULL)
1884 *resultfp = fp; /* copy out result */
1886 fdrop(fp, td); /* release local reference */
1888 if (resultfd != NULL)
1895 * Create a new open file structure without allocating a file descriptor.
1898 falloc_noinstall(struct thread *td, struct file **resultfp)
1901 int maxuserfiles = maxfiles - (maxfiles / 20);
1903 static struct timeval lastfail;
1906 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1908 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1909 if ((openfiles_new >= maxuserfiles &&
1910 priv_check(td, PRIV_MAXFILES) != 0) ||
1911 openfiles_new >= maxfiles) {
1912 atomic_subtract_int(&openfiles, 1);
1913 if (ppsratecheck(&lastfail, &curfail, 1)) {
1914 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1915 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1919 fp = uma_zalloc(file_zone, M_WAITOK);
1920 bzero(fp, sizeof(*fp));
1921 refcount_init(&fp->f_count, 1);
1922 fp->f_cred = crhold(td->td_ucred);
1923 fp->f_ops = &badfileops;
1929 * Install a file in a file descriptor table.
1932 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1933 struct filecaps *fcaps)
1935 struct filedescent *fde;
1939 filecaps_validate(fcaps, __func__);
1940 FILEDESC_XLOCK_ASSERT(fdp);
1942 fde = &fdp->fd_ofiles[fd];
1944 seqc_write_begin(&fde->fde_seqc);
1947 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1949 filecaps_move(fcaps, &fde->fde_caps);
1951 filecaps_fill(&fde->fde_caps);
1953 seqc_write_end(&fde->fde_seqc);
1958 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1959 struct filecaps *fcaps)
1961 struct filedesc *fdp = td->td_proc->p_fd;
1968 FILEDESC_XLOCK(fdp);
1969 error = fdalloc(td, 0, fd);
1970 if (__predict_false(error != 0)) {
1971 FILEDESC_XUNLOCK(fdp);
1975 _finstall(fdp, fp, *fd, flags, fcaps);
1976 FILEDESC_XUNLOCK(fdp);
1981 * Build a new filedesc structure from another.
1982 * Copy the current, root, and jail root vnode references.
1984 * If fdp is not NULL, return with it shared locked.
1987 fdinit(struct filedesc *fdp, bool prepfiles)
1989 struct filedesc0 *newfdp0;
1990 struct filedesc *newfdp;
1993 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1994 newfdp = &newfdp0->fd_fd;
1996 /* Create the file descriptor table. */
1997 FILEDESC_LOCK_INIT(newfdp);
1998 refcount_init(&newfdp->fd_refcnt, 1);
1999 refcount_init(&newfdp->fd_holdcnt, 1);
2000 newfdp->fd_cmask = CMASK;
2001 newfdp->fd_map = newfdp0->fd_dmap;
2002 newfdp->fd_lastfile = -1;
2003 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2004 newfdp->fd_files->fdt_nfiles = NDFILE;
2007 newpwd = pwd_alloc();
2008 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2012 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2013 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2015 FILEDESC_SLOCK(fdp);
2016 newpwd = pwd_hold_filedesc(fdp);
2017 smr_serialized_store(&newfdp->fd_pwd, newpwd, true);
2020 FILEDESC_SUNLOCK(fdp);
2022 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2023 FILEDESC_SUNLOCK(fdp);
2024 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2025 FILEDESC_SLOCK(fdp);
2032 static struct filedesc *
2033 fdhold(struct proc *p)
2035 struct filedesc *fdp;
2037 PROC_LOCK_ASSERT(p, MA_OWNED);
2040 refcount_acquire(&fdp->fd_holdcnt);
2045 fddrop(struct filedesc *fdp)
2048 if (fdp->fd_holdcnt > 1) {
2049 if (refcount_release(&fdp->fd_holdcnt) == 0)
2053 FILEDESC_LOCK_DESTROY(fdp);
2054 uma_zfree(filedesc0_zone, fdp);
2058 * Share a filedesc structure.
2061 fdshare(struct filedesc *fdp)
2064 refcount_acquire(&fdp->fd_refcnt);
2069 * Unshare a filedesc structure, if necessary by making a copy
2072 fdunshare(struct thread *td)
2074 struct filedesc *tmp;
2075 struct proc *p = td->td_proc;
2077 if (p->p_fd->fd_refcnt == 1)
2080 tmp = fdcopy(p->p_fd);
2086 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2090 td->td_proc->p_fd = fdp;
2094 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2095 * this is to ease callers, not catch errors.
2098 fdcopy(struct filedesc *fdp)
2100 struct filedesc *newfdp;
2101 struct filedescent *nfde, *ofde;
2106 newfdp = fdinit(fdp, true);
2107 /* copy all passable descriptors (i.e. not kqueue) */
2108 newfdp->fd_freefile = -1;
2109 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2110 ofde = &fdp->fd_ofiles[i];
2111 if (ofde->fde_file == NULL ||
2112 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2113 !fhold(ofde->fde_file)) {
2114 if (newfdp->fd_freefile == -1)
2115 newfdp->fd_freefile = i;
2118 nfde = &newfdp->fd_ofiles[i];
2120 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2121 fdused_init(newfdp, i);
2122 newfdp->fd_lastfile = i;
2124 if (newfdp->fd_freefile == -1)
2125 newfdp->fd_freefile = i;
2126 newfdp->fd_cmask = fdp->fd_cmask;
2127 FILEDESC_SUNLOCK(fdp);
2132 * Copies a filedesc structure, while remapping all file descriptors
2133 * stored inside using a translation table.
2135 * File descriptors are copied over to the new file descriptor table,
2136 * regardless of whether the close-on-exec flag is set.
2139 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2140 struct filedesc **ret)
2142 struct filedesc *newfdp;
2143 struct filedescent *nfde, *ofde;
2148 newfdp = fdinit(fdp, true);
2149 if (nfds > fdp->fd_lastfile + 1) {
2150 /* New table cannot be larger than the old one. */
2154 /* Copy all passable descriptors (i.e. not kqueue). */
2155 newfdp->fd_freefile = nfds;
2156 for (i = 0; i < nfds; ++i) {
2157 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2158 /* File descriptor out of bounds. */
2162 ofde = &fdp->fd_ofiles[fds[i]];
2163 if (ofde->fde_file == NULL) {
2164 /* Unused file descriptor. */
2168 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2169 /* File descriptor cannot be passed. */
2173 if (!fhold(nfde->fde_file)) {
2177 nfde = &newfdp->fd_ofiles[i];
2179 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2180 fdused_init(newfdp, i);
2181 newfdp->fd_lastfile = i;
2183 newfdp->fd_cmask = fdp->fd_cmask;
2184 FILEDESC_SUNLOCK(fdp);
2188 FILEDESC_SUNLOCK(fdp);
2189 fdescfree_remapped(newfdp);
2194 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2195 * one of processes using it exits) and the table used to be shared.
2198 fdclearlocks(struct thread *td)
2200 struct filedesc *fdp;
2201 struct filedesc_to_leader *fdtol;
2211 MPASS(fdtol != NULL);
2213 FILEDESC_XLOCK(fdp);
2214 KASSERT(fdtol->fdl_refcount > 0,
2215 ("filedesc_to_refcount botch: fdl_refcount=%d",
2216 fdtol->fdl_refcount));
2217 if (fdtol->fdl_refcount == 1 &&
2218 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2219 for (i = 0; i <= fdp->fd_lastfile; i++) {
2220 fp = fdp->fd_ofiles[i].fde_file;
2221 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2224 FILEDESC_XUNLOCK(fdp);
2225 lf.l_whence = SEEK_SET;
2228 lf.l_type = F_UNLCK;
2230 (void) VOP_ADVLOCK(vp,
2231 (caddr_t)p->p_leader, F_UNLCK,
2233 FILEDESC_XLOCK(fdp);
2238 if (fdtol->fdl_refcount == 1) {
2239 if (fdp->fd_holdleaderscount > 0 &&
2240 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2242 * close() or kern_dup() has cleared a reference
2243 * in a shared file descriptor table.
2245 fdp->fd_holdleaderswakeup = 1;
2246 sx_sleep(&fdp->fd_holdleaderscount,
2247 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2250 if (fdtol->fdl_holdcount > 0) {
2252 * Ensure that fdtol->fdl_leader remains
2253 * valid in closef().
2255 fdtol->fdl_wakeup = 1;
2256 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2261 fdtol->fdl_refcount--;
2262 if (fdtol->fdl_refcount == 0 &&
2263 fdtol->fdl_holdcount == 0) {
2264 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2265 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2269 FILEDESC_XUNLOCK(fdp);
2271 free(fdtol, M_FILEDESC_TO_LEADER);
2275 * Release a filedesc structure.
2278 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2280 struct filedesc0 *fdp0;
2281 struct freetable *ft, *tft;
2282 struct filedescent *fde;
2286 for (i = 0; i <= fdp->fd_lastfile; i++) {
2287 fde = &fdp->fd_ofiles[i];
2292 (void) closef(fp, td);
2298 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2299 free(fdp->fd_map, M_FILEDESC);
2300 if (fdp->fd_nfiles > NDFILE)
2301 free(fdp->fd_files, M_FILEDESC);
2303 fdp0 = (struct filedesc0 *)fdp;
2304 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2305 free(ft->ft_table, M_FILEDESC);
2311 fdescfree(struct thread *td)
2314 struct filedesc *fdp;
2322 if (RACCT_ENABLED())
2323 racct_set_unlocked(p, RACCT_NOFILE, 0);
2326 if (p->p_fdtol != NULL)
2333 if (refcount_release(&fdp->fd_refcnt) == 0)
2336 FILEDESC_XLOCK(fdp);
2337 pwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
2339 FILEDESC_XUNLOCK(fdp);
2343 fdescfree_fds(td, fdp, 1);
2347 fdescfree_remapped(struct filedesc *fdp)
2350 pwd_drop(smr_serialized_load(&fdp->fd_pwd, true));
2351 fdescfree_fds(curthread, fdp, 0);
2355 * For setugid programs, we don't want to people to use that setugidness
2356 * to generate error messages which write to a file which otherwise would
2357 * otherwise be off-limits to the process. We check for filesystems where
2358 * the vnode can change out from under us after execve (like [lin]procfs).
2360 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2361 * sufficient. We also don't check for setugidness since we know we are.
2364 is_unsafe(struct file *fp)
2368 if (fp->f_type != DTYPE_VNODE)
2372 return ((vp->v_vflag & VV_PROCDEP) != 0);
2376 * Make this setguid thing safe, if at all possible.
2379 fdsetugidsafety(struct thread *td)
2381 struct filedesc *fdp;
2385 fdp = td->td_proc->p_fd;
2386 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2387 MPASS(fdp->fd_nfiles >= 3);
2388 for (i = 0; i <= 2; i++) {
2389 fp = fdp->fd_ofiles[i].fde_file;
2390 if (fp != NULL && is_unsafe(fp)) {
2391 FILEDESC_XLOCK(fdp);
2392 knote_fdclose(td, i);
2394 * NULL-out descriptor prior to close to avoid
2395 * a race while close blocks.
2398 FILEDESC_XUNLOCK(fdp);
2399 (void) closef(fp, td);
2405 * If a specific file object occupies a specific file descriptor, close the
2406 * file descriptor entry and drop a reference on the file object. This is a
2407 * convenience function to handle a subsequent error in a function that calls
2408 * falloc() that handles the race that another thread might have closed the
2409 * file descriptor out from under the thread creating the file object.
2412 fdclose(struct thread *td, struct file *fp, int idx)
2414 struct filedesc *fdp = td->td_proc->p_fd;
2416 FILEDESC_XLOCK(fdp);
2417 if (fdp->fd_ofiles[idx].fde_file == fp) {
2419 FILEDESC_XUNLOCK(fdp);
2422 FILEDESC_XUNLOCK(fdp);
2426 * Close any files on exec?
2429 fdcloseexec(struct thread *td)
2431 struct filedesc *fdp;
2432 struct filedescent *fde;
2436 fdp = td->td_proc->p_fd;
2437 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2438 for (i = 0; i <= fdp->fd_lastfile; i++) {
2439 fde = &fdp->fd_ofiles[i];
2441 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2442 (fde->fde_flags & UF_EXCLOSE))) {
2443 FILEDESC_XLOCK(fdp);
2445 (void) closefp(fdp, i, fp, td, 0);
2446 FILEDESC_UNLOCK_ASSERT(fdp);
2452 * It is unsafe for set[ug]id processes to be started with file
2453 * descriptors 0..2 closed, as these descriptors are given implicit
2454 * significance in the Standard C library. fdcheckstd() will create a
2455 * descriptor referencing /dev/null for each of stdin, stdout, and
2456 * stderr that is not already open.
2459 fdcheckstd(struct thread *td)
2461 struct filedesc *fdp;
2463 int i, error, devnull;
2465 fdp = td->td_proc->p_fd;
2466 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2467 MPASS(fdp->fd_nfiles >= 3);
2469 for (i = 0; i <= 2; i++) {
2470 if (fdp->fd_ofiles[i].fde_file != NULL)
2473 save = td->td_retval[0];
2474 if (devnull != -1) {
2475 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2477 error = kern_openat(td, AT_FDCWD, "/dev/null",
2478 UIO_SYSSPACE, O_RDWR, 0);
2480 devnull = td->td_retval[0];
2481 KASSERT(devnull == i, ("we didn't get our fd"));
2484 td->td_retval[0] = save;
2492 * Internal form of close. Decrement reference count on file structure.
2493 * Note: td may be NULL when closing a file that was being passed in a
2497 closef(struct file *fp, struct thread *td)
2501 struct filedesc_to_leader *fdtol;
2502 struct filedesc *fdp;
2505 * POSIX record locking dictates that any close releases ALL
2506 * locks owned by this process. This is handled by setting
2507 * a flag in the unlock to free ONLY locks obeying POSIX
2508 * semantics, and not to free BSD-style file locks.
2509 * If the descriptor was in a message, POSIX-style locks
2510 * aren't passed with the descriptor, and the thread pointer
2511 * will be NULL. Callers should be careful only to pass a
2512 * NULL thread pointer when there really is no owning
2513 * context that might have locks, or the locks will be
2516 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2518 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2519 lf.l_whence = SEEK_SET;
2522 lf.l_type = F_UNLCK;
2523 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2524 F_UNLCK, &lf, F_POSIX);
2526 fdtol = td->td_proc->p_fdtol;
2527 if (fdtol != NULL) {
2529 * Handle special case where file descriptor table is
2530 * shared between multiple process leaders.
2532 fdp = td->td_proc->p_fd;
2533 FILEDESC_XLOCK(fdp);
2534 for (fdtol = fdtol->fdl_next;
2535 fdtol != td->td_proc->p_fdtol;
2536 fdtol = fdtol->fdl_next) {
2537 if ((fdtol->fdl_leader->p_flag &
2540 fdtol->fdl_holdcount++;
2541 FILEDESC_XUNLOCK(fdp);
2542 lf.l_whence = SEEK_SET;
2545 lf.l_type = F_UNLCK;
2547 (void) VOP_ADVLOCK(vp,
2548 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2550 FILEDESC_XLOCK(fdp);
2551 fdtol->fdl_holdcount--;
2552 if (fdtol->fdl_holdcount == 0 &&
2553 fdtol->fdl_wakeup != 0) {
2554 fdtol->fdl_wakeup = 0;
2558 FILEDESC_XUNLOCK(fdp);
2561 return (fdrop(fp, td));
2565 * Initialize the file pointer with the specified properties.
2567 * The ops are set with release semantics to be certain that the flags, type,
2568 * and data are visible when ops is. This is to prevent ops methods from being
2569 * called with bad data.
2572 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2577 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2581 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2582 struct file **fpp, struct filecaps *havecapsp)
2584 struct filedescent *fde;
2587 FILEDESC_LOCK_ASSERT(fdp);
2589 fde = fdeget_locked(fdp, fd);
2596 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2601 if (havecapsp != NULL)
2602 filecaps_copy(&fde->fde_caps, havecapsp, true);
2604 *fpp = fde->fde_file;
2612 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2613 struct file **fpp, struct filecaps *havecapsp)
2615 struct filedesc *fdp = td->td_proc->p_fd;
2617 #ifndef CAPABILITIES
2618 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2619 if (havecapsp != NULL && error == 0)
2620 filecaps_fill(havecapsp);
2627 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2631 if (havecapsp != NULL) {
2632 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2633 havecapsp, false)) {
2639 if (!fd_modified(fdp, fd, seq))
2648 FILEDESC_SLOCK(fdp);
2649 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2650 if (error == 0 && !fhold(*fpp))
2652 FILEDESC_SUNLOCK(fdp);
2658 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2659 struct file **fpp, seqc_t *seqp)
2662 const struct filedescent *fde;
2664 const struct fdescenttbl *fdt;
2668 cap_rights_t haverights;
2672 fdt = fdp->fd_files;
2673 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2676 * Fetch the descriptor locklessly. We avoid fdrop() races by
2677 * never raising a refcount above 0. To accomplish this we have
2678 * to use a cmpset loop rather than an atomic_add. The descriptor
2679 * must be re-verified once we acquire a reference to be certain
2680 * that the identity is still correct and we did not lose a race
2681 * due to preemption.
2685 seq = seqc_read(fd_seqc(fdt, fd));
2686 fde = &fdt->fdt_ofiles[fd];
2687 haverights = *cap_rights_fde_inline(fde);
2689 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2692 fp = fdt->fdt_ofiles[fd].fde_file;
2697 error = cap_check_inline(&haverights, needrightsp);
2701 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2703 * The count was found either saturated or zero.
2704 * This re-read is not any more racy than using the
2705 * return value from fcmpset.
2707 if (fp->f_count != 0)
2710 * Force a reload. Other thread could reallocate the
2711 * table before this fd was closed, so it is possible
2712 * that there is a stale fp pointer in cached version.
2714 fdt = atomic_load_ptr(&fdp->fd_files);
2718 * Use an acquire barrier to force re-reading of fdt so it is
2719 * refreshed for verification.
2721 atomic_thread_fence_acq();
2722 fdt = fdp->fd_files;
2724 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2726 if (fp == fdt->fdt_ofiles[fd].fde_file)
2729 fdrop(fp, curthread);
2741 * See the comments in fget_unlocked_seq for an explanation of how this works.
2743 * This is a simplified variant which bails out to the aforementioned routine
2744 * if anything goes wrong. In practice this only happens when userspace is
2745 * racing with itself.
2748 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2752 const struct filedescent *fde;
2754 const struct fdescenttbl *fdt;
2758 const cap_rights_t *haverights;
2761 fdt = fdp->fd_files;
2762 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2765 seq = seqc_read_any(fd_seqc(fdt, fd));
2766 if (__predict_false(seqc_in_modify(seq)))
2768 fde = &fdt->fdt_ofiles[fd];
2769 haverights = cap_rights_fde_inline(fde);
2772 fp = fdt->fdt_ofiles[fd].fde_file;
2774 if (__predict_false(fp == NULL))
2777 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2780 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2784 * Use an acquire barrier to force re-reading of fdt so it is
2785 * refreshed for verification.
2787 atomic_thread_fence_acq();
2788 fdt = fdp->fd_files;
2790 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2792 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2798 fdrop(fp, curthread);
2800 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2804 * Extract the file pointer associated with the specified descriptor for the
2805 * current user process.
2807 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2810 * File's rights will be checked against the capability rights mask.
2812 * If an error occurred the non-zero error is returned and *fpp is set to
2813 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2814 * responsible for fdrop().
2817 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2818 cap_rights_t *needrightsp)
2820 struct filedesc *fdp;
2825 fdp = td->td_proc->p_fd;
2826 error = fget_unlocked(fdp, fd, needrightsp, &fp);
2827 if (__predict_false(error != 0))
2829 if (__predict_false(fp->f_ops == &badfileops)) {
2835 * FREAD and FWRITE failure return EBADF as per POSIX.
2841 if ((fp->f_flag & flags) == 0)
2845 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2846 ((fp->f_flag & FWRITE) != 0))
2852 KASSERT(0, ("wrong flags"));
2865 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2868 return (_fget(td, fd, fpp, 0, rightsp));
2872 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2876 #ifndef CAPABILITIES
2877 error = _fget(td, fd, fpp, 0, rightsp);
2878 if (maxprotp != NULL)
2879 *maxprotp = VM_PROT_ALL;
2882 cap_rights_t fdrights;
2883 struct filedesc *fdp;
2888 fdp = td->td_proc->p_fd;
2889 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2891 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2892 if (__predict_false(error != 0))
2894 if (__predict_false(fp->f_ops == &badfileops)) {
2898 if (maxprotp != NULL)
2899 fdrights = *cap_rights(fdp, fd);
2900 if (!fd_modified(fdp, fd, seq))
2906 * If requested, convert capability rights to access flags.
2908 if (maxprotp != NULL)
2909 *maxprotp = cap_rights_to_vmprot(&fdrights);
2916 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2919 return (_fget(td, fd, fpp, FREAD, rightsp));
2923 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2926 return (_fget(td, fd, fpp, FWRITE, rightsp));
2930 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2933 struct filedesc *fdp = td->td_proc->p_fd;
2934 #ifndef CAPABILITIES
2935 return (fget_unlocked(fdp, fd, rightsp, fpp));
2942 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2944 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2947 error = cap_fcntl_check(fdp, fd, needfcntl);
2948 if (!fd_modified(fdp, fd, seq))
2962 * Like fget() but loads the underlying vnode, or returns an error if the
2963 * descriptor does not represent a vnode. Note that pipes use vnodes but
2964 * never have VM objects. The returned vnode will be vref()'d.
2966 * XXX: what about the unused flags ?
2969 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2976 error = _fget(td, fd, &fp, flags, needrightsp);
2979 if (fp->f_vnode == NULL) {
2991 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2994 return (_fgetvp(td, fd, 0, rightsp, vpp));
2998 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2999 struct filecaps *havecaps, struct vnode **vpp)
3001 struct filecaps caps;
3005 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3008 if (fp->f_ops == &badfileops) {
3012 if (fp->f_vnode == NULL) {
3024 filecaps_free(&caps);
3030 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3033 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3037 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3040 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3045 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3049 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3054 * Handle the last reference to a file being closed.
3056 * Without the noinline attribute clang keeps inlining the func thorough this
3057 * file when fdrop is used.
3060 _fdrop(struct file *fp, struct thread *td)
3064 if (fp->f_count != 0)
3065 panic("fdrop: count %d", fp->f_count);
3066 error = fo_close(fp, td);
3067 atomic_subtract_int(&openfiles, 1);
3069 free(fp->f_advice, M_FADVISE);
3070 uma_zfree(file_zone, fp);
3076 * Apply an advisory lock on a file descriptor.
3078 * Just attempt to get a record lock of the requested type on the entire file
3079 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3081 #ifndef _SYS_SYSPROTO_H_
3089 sys_flock(struct thread *td, struct flock_args *uap)
3096 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3099 if (fp->f_type != DTYPE_VNODE) {
3101 return (EOPNOTSUPP);
3105 lf.l_whence = SEEK_SET;
3108 if (uap->how & LOCK_UN) {
3109 lf.l_type = F_UNLCK;
3110 atomic_clear_int(&fp->f_flag, FHASLOCK);
3111 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3114 if (uap->how & LOCK_EX)
3115 lf.l_type = F_WRLCK;
3116 else if (uap->how & LOCK_SH)
3117 lf.l_type = F_RDLCK;
3122 atomic_set_int(&fp->f_flag, FHASLOCK);
3123 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3124 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3130 * Duplicate the specified descriptor to a free descriptor.
3133 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3134 int openerror, int *indxp)
3136 struct filedescent *newfde, *oldfde;
3141 KASSERT(openerror == ENODEV || openerror == ENXIO,
3142 ("unexpected error %d in %s", openerror, __func__));
3145 * If the to-be-dup'd fd number is greater than the allowed number
3146 * of file descriptors, or the fd to be dup'd has already been
3147 * closed, then reject.
3149 FILEDESC_XLOCK(fdp);
3150 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3151 FILEDESC_XUNLOCK(fdp);
3155 error = fdalloc(td, 0, &indx);
3157 FILEDESC_XUNLOCK(fdp);
3162 * There are two cases of interest here.
3164 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3166 * For ENXIO steal away the file structure from (dfd) and store it in
3167 * (indx). (dfd) is effectively closed by this operation.
3169 switch (openerror) {
3172 * Check that the mode the file is being opened for is a
3173 * subset of the mode of the existing descriptor.
3175 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3176 fdunused(fdp, indx);
3177 FILEDESC_XUNLOCK(fdp);
3181 fdunused(fdp, indx);
3182 FILEDESC_XUNLOCK(fdp);
3185 newfde = &fdp->fd_ofiles[indx];
3186 oldfde = &fdp->fd_ofiles[dfd];
3187 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3189 seqc_write_begin(&newfde->fde_seqc);
3191 memcpy(newfde, oldfde, fde_change_size);
3192 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3195 seqc_write_end(&newfde->fde_seqc);
3200 * Steal away the file pointer from dfd and stuff it into indx.
3202 newfde = &fdp->fd_ofiles[indx];
3203 oldfde = &fdp->fd_ofiles[dfd];
3205 seqc_write_begin(&newfde->fde_seqc);
3207 memcpy(newfde, oldfde, fde_change_size);
3208 oldfde->fde_file = NULL;
3211 seqc_write_end(&newfde->fde_seqc);
3215 FILEDESC_XUNLOCK(fdp);
3221 * This sysctl determines if we will allow a process to chroot(2) if it
3222 * has a directory open:
3223 * 0: disallowed for all processes.
3224 * 1: allowed for processes that were not already chroot(2)'ed.
3225 * 2: allowed for all processes.
3228 static int chroot_allow_open_directories = 1;
3230 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3231 &chroot_allow_open_directories, 0,
3232 "Allow a process to chroot(2) if it has a directory open");
3235 * Helper function for raised chroot(2) security function: Refuse if
3236 * any filedescriptors are open directories.
3239 chroot_refuse_vdir_fds(struct filedesc *fdp)
3245 FILEDESC_LOCK_ASSERT(fdp);
3247 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3248 fp = fget_locked(fdp, fd);
3251 if (fp->f_type == DTYPE_VNODE) {
3253 if (vp->v_type == VDIR)
3261 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3264 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3265 vrefact(oldpwd->pwd_cdir);
3266 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3269 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3270 vrefact(oldpwd->pwd_rdir);
3271 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3274 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3275 vrefact(oldpwd->pwd_jdir);
3276 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3281 pwd_hold_filedesc(struct filedesc *fdp)
3285 FILEDESC_LOCK_ASSERT(fdp);
3286 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
3288 refcount_acquire(&pwd->pwd_refcount);
3293 pwd_hold(struct thread *td)
3295 struct filedesc *fdp;
3298 fdp = td->td_proc->p_fd;
3302 pwd = smr_entered_load(&fdp->fd_pwd, pwd_smr);
3304 if (refcount_acquire_if_not_zero(&pwd->pwd_refcount))
3316 pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3317 bzero(pwd, sizeof(*pwd));
3318 refcount_init(&pwd->pwd_refcount, 1);
3323 pwd_drop(struct pwd *pwd)
3326 if (!refcount_release(&pwd->pwd_refcount))
3329 if (pwd->pwd_cdir != NULL)
3330 vrele(pwd->pwd_cdir);
3331 if (pwd->pwd_rdir != NULL)
3332 vrele(pwd->pwd_rdir);
3333 if (pwd->pwd_jdir != NULL)
3334 vrele(pwd->pwd_jdir);
3335 uma_zfree_smr(pwd_zone, pwd);
3339 * Common routine for kern_chroot() and jail_attach(). The caller is
3340 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3341 * authorize this operation.
3344 pwd_chroot(struct thread *td, struct vnode *vp)
3346 struct filedesc *fdp;
3347 struct pwd *newpwd, *oldpwd;
3350 fdp = td->td_proc->p_fd;
3351 newpwd = pwd_alloc();
3352 FILEDESC_XLOCK(fdp);
3353 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3354 if (chroot_allow_open_directories == 0 ||
3355 (chroot_allow_open_directories == 1 &&
3356 oldpwd->pwd_rdir != rootvnode)) {
3357 error = chroot_refuse_vdir_fds(fdp);
3359 FILEDESC_XUNLOCK(fdp);
3366 newpwd->pwd_rdir = vp;
3367 if (oldpwd->pwd_jdir == NULL) {
3369 newpwd->pwd_jdir = vp;
3371 pwd_fill(oldpwd, newpwd);
3372 pwd_set(fdp, newpwd);
3373 FILEDESC_XUNLOCK(fdp);
3379 pwd_chdir(struct thread *td, struct vnode *vp)
3381 struct filedesc *fdp;
3382 struct pwd *newpwd, *oldpwd;
3384 VNPASS(vp->v_usecount > 0, vp);
3386 newpwd = pwd_alloc();
3387 fdp = td->td_proc->p_fd;
3388 FILEDESC_XLOCK(fdp);
3389 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3390 newpwd->pwd_cdir = vp;
3391 pwd_fill(oldpwd, newpwd);
3392 pwd_set(fdp, newpwd);
3393 FILEDESC_XUNLOCK(fdp);
3398 pwd_ensure_dirs(void)
3400 struct filedesc *fdp;
3401 struct pwd *oldpwd, *newpwd;
3403 fdp = curproc->p_fd;
3404 FILEDESC_XLOCK(fdp);
3405 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3406 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3407 FILEDESC_XUNLOCK(fdp);
3410 FILEDESC_XUNLOCK(fdp);
3412 newpwd = pwd_alloc();
3413 FILEDESC_XLOCK(fdp);
3414 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3415 pwd_fill(oldpwd, newpwd);
3416 if (newpwd->pwd_cdir == NULL) {
3418 newpwd->pwd_cdir = rootvnode;
3420 if (newpwd->pwd_rdir == NULL) {
3422 newpwd->pwd_rdir = rootvnode;
3424 pwd_set(fdp, newpwd);
3425 FILEDESC_XUNLOCK(fdp);
3430 * Scan all active processes and prisons to see if any of them have a current
3431 * or root directory of `olddp'. If so, replace them with the new mount point.
3434 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3436 struct filedesc *fdp;
3437 struct pwd *newpwd, *oldpwd;
3442 if (vrefcnt(olddp) == 1)
3445 newpwd = pwd_alloc();
3446 sx_slock(&allproc_lock);
3447 FOREACH_PROC_IN_SYSTEM(p) {
3453 FILEDESC_XLOCK(fdp);
3454 oldpwd = FILEDESC_XLOCKED_LOAD_PWD(fdp);
3455 if (oldpwd == NULL ||
3456 (oldpwd->pwd_cdir != olddp &&
3457 oldpwd->pwd_rdir != olddp &&
3458 oldpwd->pwd_jdir != olddp)) {
3459 FILEDESC_XUNLOCK(fdp);
3463 if (oldpwd->pwd_cdir == olddp) {
3465 newpwd->pwd_cdir = newdp;
3467 if (oldpwd->pwd_rdir == olddp) {
3469 newpwd->pwd_rdir = newdp;
3471 if (oldpwd->pwd_jdir == olddp) {
3473 newpwd->pwd_jdir = newdp;
3475 pwd_fill(oldpwd, newpwd);
3476 pwd_set(fdp, newpwd);
3477 FILEDESC_XUNLOCK(fdp);
3480 newpwd = pwd_alloc();
3482 sx_sunlock(&allproc_lock);
3484 if (rootvnode == olddp) {
3489 mtx_lock(&prison0.pr_mtx);
3490 if (prison0.pr_root == olddp) {
3492 prison0.pr_root = newdp;
3495 mtx_unlock(&prison0.pr_mtx);
3496 sx_slock(&allprison_lock);
3497 TAILQ_FOREACH(pr, &allprison, pr_list) {
3498 mtx_lock(&pr->pr_mtx);
3499 if (pr->pr_root == olddp) {
3501 pr->pr_root = newdp;
3504 mtx_unlock(&pr->pr_mtx);
3506 sx_sunlock(&allprison_lock);
3511 struct filedesc_to_leader *
3512 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3514 struct filedesc_to_leader *fdtol;
3516 fdtol = malloc(sizeof(struct filedesc_to_leader),
3517 M_FILEDESC_TO_LEADER, M_WAITOK);
3518 fdtol->fdl_refcount = 1;
3519 fdtol->fdl_holdcount = 0;
3520 fdtol->fdl_wakeup = 0;
3521 fdtol->fdl_leader = leader;
3523 FILEDESC_XLOCK(fdp);
3524 fdtol->fdl_next = old->fdl_next;
3525 fdtol->fdl_prev = old;
3526 old->fdl_next = fdtol;
3527 fdtol->fdl_next->fdl_prev = fdtol;
3528 FILEDESC_XUNLOCK(fdp);
3530 fdtol->fdl_next = fdtol;
3531 fdtol->fdl_prev = fdtol;
3537 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3539 struct filedesc *fdp;
3540 int i, count, slots;
3542 if (*(int *)arg1 != 0)
3545 fdp = curproc->p_fd;
3547 FILEDESC_SLOCK(fdp);
3548 slots = NDSLOTS(fdp->fd_lastfile + 1);
3549 for (i = 0; i < slots; i++)
3550 count += bitcountl(fdp->fd_map[i]);
3551 FILEDESC_SUNLOCK(fdp);
3553 return (SYSCTL_OUT(req, &count, sizeof(count)));
3556 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3557 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3558 "Number of open file descriptors");
3561 * Get file structures globally.
3564 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3567 struct filedesc *fdp;
3572 error = sysctl_wire_old_buffer(req, 0);
3575 if (req->oldptr == NULL) {
3577 sx_slock(&allproc_lock);
3578 FOREACH_PROC_IN_SYSTEM(p) {
3580 if (p->p_state == PRS_NEW) {
3588 /* overestimates sparse tables. */
3589 if (fdp->fd_lastfile > 0)
3590 n += fdp->fd_lastfile;
3593 sx_sunlock(&allproc_lock);
3594 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3597 bzero(&xf, sizeof(xf));
3598 xf.xf_size = sizeof(xf);
3599 sx_slock(&allproc_lock);
3600 FOREACH_PROC_IN_SYSTEM(p) {
3602 if (p->p_state == PRS_NEW) {
3606 if (p_cansee(req->td, p) != 0) {
3610 xf.xf_pid = p->p_pid;
3611 xf.xf_uid = p->p_ucred->cr_uid;
3616 FILEDESC_SLOCK(fdp);
3617 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3618 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3621 xf.xf_file = (uintptr_t)fp;
3622 xf.xf_data = (uintptr_t)fp->f_data;
3623 xf.xf_vnode = (uintptr_t)fp->f_vnode;
3624 xf.xf_type = (uintptr_t)fp->f_type;
3625 xf.xf_count = fp->f_count;
3627 xf.xf_offset = foffset_get(fp);
3628 xf.xf_flag = fp->f_flag;
3629 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3633 FILEDESC_SUNLOCK(fdp);
3638 sx_sunlock(&allproc_lock);
3642 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3643 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3645 #ifdef KINFO_FILE_SIZE
3646 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3650 xlate_fflags(int fflags)
3652 static const struct {
3655 } fflags_table[] = {
3656 { FAPPEND, KF_FLAG_APPEND },
3657 { FASYNC, KF_FLAG_ASYNC },
3658 { FFSYNC, KF_FLAG_FSYNC },
3659 { FHASLOCK, KF_FLAG_HASLOCK },
3660 { FNONBLOCK, KF_FLAG_NONBLOCK },
3661 { FREAD, KF_FLAG_READ },
3662 { FWRITE, KF_FLAG_WRITE },
3663 { O_CREAT, KF_FLAG_CREAT },
3664 { O_DIRECT, KF_FLAG_DIRECT },
3665 { O_EXCL, KF_FLAG_EXCL },
3666 { O_EXEC, KF_FLAG_EXEC },
3667 { O_EXLOCK, KF_FLAG_EXLOCK },
3668 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3669 { O_SHLOCK, KF_FLAG_SHLOCK },
3670 { O_TRUNC, KF_FLAG_TRUNC }
3676 for (i = 0; i < nitems(fflags_table); i++)
3677 if (fflags & fflags_table[i].fflag)
3678 kflags |= fflags_table[i].kf_fflag;
3682 /* Trim unused data from kf_path by truncating the structure size. */
3684 pack_kinfo(struct kinfo_file *kif)
3687 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3688 strlen(kif->kf_path) + 1;
3689 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3693 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3694 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3698 bzero(kif, sizeof(*kif));
3700 /* Set a default type to allow for empty fill_kinfo() methods. */
3701 kif->kf_type = KF_TYPE_UNKNOWN;
3702 kif->kf_flags = xlate_fflags(fp->f_flag);
3703 if (rightsp != NULL)
3704 kif->kf_cap_rights = *rightsp;
3706 cap_rights_init_zero(&kif->kf_cap_rights);
3708 kif->kf_ref_count = fp->f_count;
3709 kif->kf_offset = foffset_get(fp);
3712 * This may drop the filedesc lock, so the 'fp' cannot be
3713 * accessed after this call.
3715 error = fo_fill_kinfo(fp, kif, fdp);
3717 kif->kf_status |= KF_ATTR_VALID;
3718 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3721 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3725 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3726 struct kinfo_file *kif, int flags)
3730 bzero(kif, sizeof(*kif));
3732 kif->kf_type = KF_TYPE_VNODE;
3733 error = vn_fill_kinfo_vnode(vp, kif);
3735 kif->kf_status |= KF_ATTR_VALID;
3736 kif->kf_flags = xlate_fflags(fflags);
3737 cap_rights_init_zero(&kif->kf_cap_rights);
3739 kif->kf_ref_count = -1;
3740 kif->kf_offset = -1;
3741 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3744 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3748 struct export_fd_buf {
3749 struct filedesc *fdp;
3752 struct kinfo_file kif;
3757 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3759 struct kinfo_file *kif;
3762 if (efbuf->remainder != -1) {
3763 if (efbuf->remainder < kif->kf_structsize) {
3764 /* Terminate export. */
3765 efbuf->remainder = 0;
3768 efbuf->remainder -= kif->kf_structsize;
3770 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3774 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3775 struct export_fd_buf *efbuf)
3779 if (efbuf->remainder == 0)
3781 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3783 FILEDESC_SUNLOCK(efbuf->fdp);
3784 error = export_kinfo_to_sb(efbuf);
3785 FILEDESC_SLOCK(efbuf->fdp);
3790 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3791 struct export_fd_buf *efbuf)
3795 if (efbuf->remainder == 0)
3797 if (efbuf->fdp != NULL)
3798 FILEDESC_SUNLOCK(efbuf->fdp);
3799 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3800 error = export_kinfo_to_sb(efbuf);
3801 if (efbuf->fdp != NULL)
3802 FILEDESC_SLOCK(efbuf->fdp);
3807 * Store a process file descriptor information to sbuf.
3809 * Takes a locked proc as argument, and returns with the proc unlocked.
3812 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3816 struct filedesc *fdp;
3817 struct export_fd_buf *efbuf;
3818 struct vnode *cttyvp, *textvp, *tracevp;
3821 cap_rights_t rights;
3823 PROC_LOCK_ASSERT(p, MA_OWNED);
3826 tracevp = p->p_tracevp;
3827 if (tracevp != NULL)
3830 textvp = p->p_textvp;
3833 /* Controlling tty. */
3835 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3836 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3842 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3845 efbuf->remainder = maxlen;
3846 efbuf->flags = flags;
3847 if (tracevp != NULL)
3848 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3851 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3853 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3859 FILEDESC_SLOCK(fdp);
3860 pwd = pwd_hold_filedesc(fdp);
3862 /* working directory */
3863 if (pwd->pwd_cdir != NULL) {
3864 vrefact(pwd->pwd_cdir);
3865 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3867 /* root directory */
3868 if (pwd->pwd_rdir != NULL) {
3869 vrefact(pwd->pwd_rdir);
3870 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3872 /* jail directory */
3873 if (pwd->pwd_jdir != NULL) {
3874 vrefact(pwd->pwd_jdir);
3875 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3879 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3880 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3883 rights = *cap_rights(fdp, i);
3884 #else /* !CAPABILITIES */
3885 rights = cap_no_rights;
3888 * Create sysctl entry. It is OK to drop the filedesc
3889 * lock inside of export_file_to_sb() as we will
3890 * re-validate and re-evaluate its properties when the
3893 error = export_file_to_sb(fp, i, &rights, efbuf);
3894 if (error != 0 || efbuf->remainder == 0)
3897 FILEDESC_SUNLOCK(fdp);
3900 free(efbuf, M_TEMP);
3904 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3907 * Get per-process file descriptors for use by procstat(1), et al.
3910 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3915 int error, error2, *name;
3919 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3920 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3921 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3926 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3927 error = kern_proc_filedesc_out(p, &sb, maxlen,
3928 KERN_FILEDESC_PACK_KINFO);
3929 error2 = sbuf_finish(&sb);
3931 return (error != 0 ? error : error2);
3934 #ifdef COMPAT_FREEBSD7
3935 #ifdef KINFO_OFILE_SIZE
3936 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3940 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3943 okif->kf_structsize = sizeof(*okif);
3944 okif->kf_type = kif->kf_type;
3945 okif->kf_fd = kif->kf_fd;
3946 okif->kf_ref_count = kif->kf_ref_count;
3947 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3948 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3949 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3950 okif->kf_offset = kif->kf_offset;
3951 if (kif->kf_type == KF_TYPE_VNODE)
3952 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
3954 okif->kf_vnode_type = KF_VTYPE_VNON;
3955 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3956 if (kif->kf_type == KF_TYPE_SOCKET) {
3957 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
3958 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
3959 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
3960 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
3961 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
3963 okif->kf_sa_local.ss_family = AF_UNSPEC;
3964 okif->kf_sa_peer.ss_family = AF_UNSPEC;
3969 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3970 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3975 FILEDESC_SUNLOCK(fdp);
3976 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3977 kinfo_to_okinfo(kif, okif);
3978 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3979 FILEDESC_SLOCK(fdp);
3984 * Get per-process file descriptors for use by procstat(1), et al.
3987 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3989 struct kinfo_ofile *okif;
3990 struct kinfo_file *kif;
3991 struct filedesc *fdp;
3993 int error, i, *name;
3998 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4005 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4006 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4007 FILEDESC_SLOCK(fdp);
4008 pwd = pwd_hold_filedesc(fdp);
4010 if (pwd->pwd_cdir != NULL)
4011 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4013 if (pwd->pwd_rdir != NULL)
4014 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4016 if (pwd->pwd_jdir != NULL)
4017 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4021 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4022 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4024 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4025 KERN_FILEDESC_PACK_KINFO);
4026 FILEDESC_SUNLOCK(fdp);
4027 kinfo_to_okinfo(kif, okif);
4028 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4029 FILEDESC_SLOCK(fdp);
4033 FILEDESC_SUNLOCK(fdp);
4040 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4041 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4042 "Process ofiledesc entries");
4043 #endif /* COMPAT_FREEBSD7 */
4046 vntype_to_kinfo(int vtype)
4051 } vtypes_table[] = {
4052 { VBAD, KF_VTYPE_VBAD },
4053 { VBLK, KF_VTYPE_VBLK },
4054 { VCHR, KF_VTYPE_VCHR },
4055 { VDIR, KF_VTYPE_VDIR },
4056 { VFIFO, KF_VTYPE_VFIFO },
4057 { VLNK, KF_VTYPE_VLNK },
4058 { VNON, KF_VTYPE_VNON },
4059 { VREG, KF_VTYPE_VREG },
4060 { VSOCK, KF_VTYPE_VSOCK }
4065 * Perform vtype translation.
4067 for (i = 0; i < nitems(vtypes_table); i++)
4068 if (vtypes_table[i].vtype == vtype)
4069 return (vtypes_table[i].kf_vtype);
4071 return (KF_VTYPE_UNKNOWN);
4074 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4075 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4076 "Process filedesc entries");
4079 * Store a process current working directory information to sbuf.
4081 * Takes a locked proc as argument, and returns with the proc unlocked.
4084 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4086 struct filedesc *fdp;
4088 struct export_fd_buf *efbuf;
4092 PROC_LOCK_ASSERT(p, MA_OWNED);
4099 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4102 efbuf->remainder = maxlen;
4104 FILEDESC_SLOCK(fdp);
4105 pwd = FILEDESC_LOCKED_LOAD_PWD(fdp);
4106 cdir = pwd->pwd_cdir;
4111 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4113 FILEDESC_SUNLOCK(fdp);
4115 free(efbuf, M_TEMP);
4120 * Get per-process current working directory.
4123 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4128 int error, error2, *name;
4132 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4133 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4134 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4139 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4140 error = kern_proc_cwd_out(p, &sb, maxlen);
4141 error2 = sbuf_finish(&sb);
4143 return (error != 0 ? error : error2);
4146 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4147 sysctl_kern_proc_cwd, "Process current working directory");
4151 * For the purposes of debugging, generate a human-readable string for the
4155 file_type_to_name(short type)
4183 case DTYPE_PROCDESC:
4185 case DTYPE_LINUXEFD:
4187 case DTYPE_LINUXTFD:
4195 * For the purposes of debugging, identify a process (if any, perhaps one of
4196 * many) that references the passed file in its file descriptor array. Return
4199 static struct proc *
4200 file_to_first_proc(struct file *fp)
4202 struct filedesc *fdp;
4206 FOREACH_PROC_IN_SYSTEM(p) {
4207 if (p->p_state == PRS_NEW)
4212 for (n = 0; n <= fdp->fd_lastfile; n++) {
4213 if (fp == fdp->fd_ofiles[n].fde_file)
4221 db_print_file(struct file *fp, int header)
4223 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4227 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4228 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4229 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4231 p = file_to_first_proc(fp);
4232 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4233 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4234 fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4235 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4240 DB_SHOW_COMMAND(file, db_show_file)
4245 db_printf("usage: show file <addr>\n");
4248 fp = (struct file *)addr;
4249 db_print_file(fp, 1);
4252 DB_SHOW_COMMAND(files, db_show_files)
4254 struct filedesc *fdp;
4261 FOREACH_PROC_IN_SYSTEM(p) {
4262 if (p->p_state == PRS_NEW)
4264 if ((fdp = p->p_fd) == NULL)
4266 for (n = 0; n <= fdp->fd_lastfile; ++n) {
4267 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4269 db_print_file(fp, header);
4276 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4277 &maxfilesperproc, 0, "Maximum files allowed open per process");
4279 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4280 &maxfiles, 0, "Maximum number of files");
4282 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4283 &openfiles, 0, "System-wide number of open files");
4287 filelistinit(void *dummy)
4290 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4291 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4292 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4293 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4294 pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
4295 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
4296 pwd_smr = uma_zone_get_smr(pwd_zone);
4297 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4299 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4301 /*-------------------------------------------------------------------*/
4304 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4305 int flags, struct thread *td)
4312 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4320 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4328 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4336 badfo_kqfilter(struct file *fp, struct knote *kn)
4343 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4351 badfo_close(struct file *fp, struct thread *td)
4358 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4366 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4374 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4375 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4383 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4389 struct fileops badfileops = {
4390 .fo_read = badfo_readwrite,
4391 .fo_write = badfo_readwrite,
4392 .fo_truncate = badfo_truncate,
4393 .fo_ioctl = badfo_ioctl,
4394 .fo_poll = badfo_poll,
4395 .fo_kqfilter = badfo_kqfilter,
4396 .fo_stat = badfo_stat,
4397 .fo_close = badfo_close,
4398 .fo_chmod = badfo_chmod,
4399 .fo_chown = badfo_chown,
4400 .fo_sendfile = badfo_sendfile,
4401 .fo_fill_kinfo = badfo_fill_kinfo,
4405 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4406 int flags, struct thread *td)
4409 return (EOPNOTSUPP);
4413 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4421 invfo_ioctl(struct file *fp, u_long com, void *data,
4422 struct ucred *active_cred, struct thread *td)
4429 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4433 return (poll_no_poll(events));
4437 invfo_kqfilter(struct file *fp, struct knote *kn)
4444 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4452 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4460 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4461 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4468 /*-------------------------------------------------------------------*/
4471 * File Descriptor pseudo-device driver (/dev/fd/).
4473 * Opening minor device N dup()s the file (if any) connected to file
4474 * descriptor N belonging to the calling process. Note that this driver
4475 * consists of only the ``open()'' routine, because all subsequent
4476 * references to this file will be direct to the other driver.
4478 * XXX: we could give this one a cloning event handler if necessary.
4483 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4487 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4488 * the file descriptor being sought for duplication. The error
4489 * return ensures that the vnode for this device will be released
4490 * by vn_open. Open will detect this special error and take the
4491 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4492 * will simply report the error.
4494 td->td_dupfd = dev2unit(dev);
4498 static struct cdevsw fildesc_cdevsw = {
4499 .d_version = D_VERSION,
4505 fildesc_drvinit(void *unused)
4509 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4510 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4511 make_dev_alias(dev, "stdin");
4512 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4513 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4514 make_dev_alias(dev, "stdout");
4515 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4516 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4517 make_dev_alias(dev, "stderr");
4520 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);