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>
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>
81 #include <sys/ktrace.h>
86 #include <security/audit/audit.h>
93 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
94 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
95 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
96 "file desc to leader structures");
97 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
98 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
100 MALLOC_DECLARE(M_FADVISE);
102 static __read_mostly uma_zone_t file_zone;
103 static __read_mostly uma_zone_t filedesc0_zone;
105 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
106 struct thread *td, int holdleaders);
107 static int fd_first_free(struct filedesc *fdp, int low, int size);
108 static int fd_last_used(struct filedesc *fdp, int size);
109 static void fdgrowtable(struct filedesc *fdp, int nfd);
110 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
111 static void fdunused(struct filedesc *fdp, int fd);
112 static void fdused(struct filedesc *fdp, int fd);
113 static int getmaxfd(struct thread *td);
114 static u_long *filecaps_copy_prep(const struct filecaps *src);
115 static void filecaps_copy_finish(const struct filecaps *src,
116 struct filecaps *dst, u_long *ioctls);
117 static u_long *filecaps_free_prep(struct filecaps *fcaps);
118 static void filecaps_free_finish(u_long *ioctls);
120 static struct pwd *pwd_alloc(void);
125 * - An array of open file descriptors (fd_ofiles)
126 * - An array of file flags (fd_ofileflags)
127 * - A bitmap recording which descriptors are in use (fd_map)
129 * A process starts out with NDFILE descriptors. The value of NDFILE has
130 * been selected based the historical limit of 20 open files, and an
131 * assumption that the majority of processes, especially short-lived
132 * processes like shells, will never need more.
134 * If this initial allocation is exhausted, a larger descriptor table and
135 * map are allocated dynamically, and the pointers in the process's struct
136 * filedesc are updated to point to those. This is repeated every time
137 * the process runs out of file descriptors (provided it hasn't hit its
140 * Since threads may hold references to individual descriptor table
141 * entries, the tables are never freed. Instead, they are placed on a
142 * linked list and freed only when the struct filedesc is released.
145 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
146 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
147 #define NDSLOT(x) ((x) / NDENTRIES)
148 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
149 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
152 * SLIST entry used to keep track of ofiles which must be reclaimed when
156 struct fdescenttbl *ft_table;
157 SLIST_ENTRY(freetable) ft_next;
161 * Initial allocation: a filedesc structure + the head of SLIST used to
162 * keep track of old ofiles + enough space for NDFILE descriptors.
165 struct fdescenttbl0 {
167 struct filedescent fdt_ofiles[NDFILE];
171 struct filedesc fd_fd;
172 SLIST_HEAD(, freetable) fd_free;
173 struct fdescenttbl0 fd_dfiles;
174 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
178 * Descriptor management.
180 static int __exclusive_cache_line openfiles; /* actual number of open files */
181 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
182 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
185 * If low >= size, just return low. Otherwise find the first zero bit in the
186 * given bitmap, starting at low and not exceeding size - 1. Return size if
190 fd_first_free(struct filedesc *fdp, int low, int size)
192 NDSLOTTYPE *map = fdp->fd_map;
200 if (low % NDENTRIES) {
201 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
202 if ((mask &= ~map[off]) != 0UL)
203 return (off * NDENTRIES + ffsl(mask) - 1);
206 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
207 if (map[off] != ~0UL)
208 return (off * NDENTRIES + ffsl(~map[off]) - 1);
213 * Find the highest non-zero bit in the given bitmap, starting at 0 and
214 * not exceeding size - 1. Return -1 if not found.
217 fd_last_used(struct filedesc *fdp, int size)
219 NDSLOTTYPE *map = fdp->fd_map;
224 if (size % NDENTRIES) {
225 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
226 if ((mask &= map[off]) != 0)
227 return (off * NDENTRIES + flsl(mask) - 1);
230 for (minoff = NDSLOT(0); off >= minoff; --off)
232 return (off * NDENTRIES + flsl(map[off]) - 1);
237 fdisused(struct filedesc *fdp, int fd)
240 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
241 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
243 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
247 * Mark a file descriptor as used.
250 fdused_init(struct filedesc *fdp, int fd)
253 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
255 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
259 fdused(struct filedesc *fdp, int fd)
262 FILEDESC_XLOCK_ASSERT(fdp);
264 fdused_init(fdp, fd);
265 if (fd > fdp->fd_lastfile)
266 fdp->fd_lastfile = fd;
267 if (fd == fdp->fd_freefile)
272 * Mark a file descriptor as unused.
275 fdunused(struct filedesc *fdp, int fd)
278 FILEDESC_XLOCK_ASSERT(fdp);
280 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
281 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
282 ("fd=%d is still in use", fd));
284 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
285 if (fd < fdp->fd_freefile)
286 fdp->fd_freefile = fd;
287 if (fd == fdp->fd_lastfile)
288 fdp->fd_lastfile = fd_last_used(fdp, fd);
292 * Free a file descriptor.
294 * Avoid some work if fdp is about to be destroyed.
297 fdefree_last(struct filedescent *fde)
300 filecaps_free(&fde->fde_caps);
304 fdfree(struct filedesc *fdp, int fd)
306 struct filedescent *fde;
308 fde = &fdp->fd_ofiles[fd];
310 seqc_write_begin(&fde->fde_seqc);
312 fde->fde_file = NULL;
314 seqc_write_end(&fde->fde_seqc);
321 * System calls on descriptors.
323 #ifndef _SYS_SYSPROTO_H_
324 struct getdtablesize_args {
330 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
336 td->td_retval[0] = getmaxfd(td);
338 PROC_LOCK(td->td_proc);
339 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
340 PROC_UNLOCK(td->td_proc);
341 if (lim < td->td_retval[0])
342 td->td_retval[0] = lim;
348 * Duplicate a file descriptor to a particular value.
350 * Note: keep in mind that a potential race condition exists when closing
351 * descriptors from a shared descriptor table (via rfork).
353 #ifndef _SYS_SYSPROTO_H_
361 sys_dup2(struct thread *td, struct dup2_args *uap)
364 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
368 * Duplicate a file descriptor.
370 #ifndef _SYS_SYSPROTO_H_
377 sys_dup(struct thread *td, struct dup_args *uap)
380 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
384 * The file control system call.
386 #ifndef _SYS_SYSPROTO_H_
395 sys_fcntl(struct thread *td, struct fcntl_args *uap)
398 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
402 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
416 * Convert old flock structure to new.
418 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
419 fl.l_start = ofl.l_start;
420 fl.l_len = ofl.l_len;
421 fl.l_pid = ofl.l_pid;
422 fl.l_type = ofl.l_type;
423 fl.l_whence = ofl.l_whence;
437 arg1 = (intptr_t)&fl;
443 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
444 arg1 = (intptr_t)&fl;
452 error = kern_fcntl(td, fd, newcmd, arg1);
455 if (cmd == F_OGETLK) {
456 ofl.l_start = fl.l_start;
457 ofl.l_len = fl.l_len;
458 ofl.l_pid = fl.l_pid;
459 ofl.l_type = fl.l_type;
460 ofl.l_whence = fl.l_whence;
461 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
462 } else if (cmd == F_GETLK) {
463 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
469 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
471 struct filedesc *fdp;
473 struct file *fp, *fp2;
474 struct filedescent *fde;
478 int error, flg, seals, tmp;
492 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
495 case F_DUPFD_CLOEXEC:
497 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
502 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
505 case F_DUP2FD_CLOEXEC:
507 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
513 fde = fdeget_locked(fdp, fd);
516 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
519 FILEDESC_SUNLOCK(fdp);
525 fde = fdeget_locked(fdp, fd);
527 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
528 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
531 FILEDESC_XUNLOCK(fdp);
535 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
538 td->td_retval[0] = OFLAGS(fp->f_flag);
543 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
547 tmp = flg = fp->f_flag;
549 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
550 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
551 tmp = fp->f_flag & FNONBLOCK;
552 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
557 tmp = fp->f_flag & FASYNC;
558 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
563 atomic_clear_int(&fp->f_flag, FNONBLOCK);
565 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
570 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
573 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
575 td->td_retval[0] = tmp;
580 error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
584 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
589 error = priv_check(td, PRIV_NFS_LOCKD);
597 /* FALLTHROUGH F_SETLK */
601 flp = (struct flock *)arg;
602 if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
607 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
610 if (fp->f_type != DTYPE_VNODE) {
616 if (flp->l_whence == SEEK_CUR) {
617 foffset = foffset_get(fp);
620 foffset > OFF_MAX - flp->l_start)) {
625 flp->l_start += foffset;
629 switch (flp->l_type) {
631 if ((fp->f_flag & FREAD) == 0) {
635 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
636 PROC_LOCK(p->p_leader);
637 p->p_leader->p_flag |= P_ADVLOCK;
638 PROC_UNLOCK(p->p_leader);
640 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
644 if ((fp->f_flag & FWRITE) == 0) {
648 if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
649 PROC_LOCK(p->p_leader);
650 p->p_leader->p_flag |= P_ADVLOCK;
651 PROC_UNLOCK(p->p_leader);
653 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
657 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
661 if (flg != F_REMOTE) {
665 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
666 F_UNLCKSYS, flp, flg);
672 if (error != 0 || flp->l_type == F_UNLCK ||
673 flp->l_type == F_UNLCKSYS) {
679 * Check for a race with close.
681 * The vnode is now advisory locked (or unlocked, but this case
682 * is not really important) as the caller requested.
683 * We had to drop the filedesc lock, so we need to recheck if
684 * the descriptor is still valid, because if it was closed
685 * in the meantime we need to remove advisory lock from the
686 * vnode - close on any descriptor leading to an advisory
687 * locked vnode, removes that lock.
688 * We will return 0 on purpose in that case, as the result of
689 * successful advisory lock might have been externally visible
690 * already. This is fine - effectively we pretend to the caller
691 * that the closing thread was a bit slower and that the
692 * advisory lock succeeded before the close.
694 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp2);
700 flp->l_whence = SEEK_SET;
703 flp->l_type = F_UNLCK;
704 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
705 F_UNLCK, flp, F_POSIX);
712 error = fget_unlocked(fdp, fd, &cap_flock_rights, &fp);
715 if (fp->f_type != DTYPE_VNODE) {
720 flp = (struct flock *)arg;
721 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
722 flp->l_type != F_UNLCK) {
727 if (flp->l_whence == SEEK_CUR) {
728 foffset = foffset_get(fp);
729 if ((flp->l_start > 0 &&
730 foffset > OFF_MAX - flp->l_start) ||
732 foffset < OFF_MIN - flp->l_start)) {
737 flp->l_start += foffset;
740 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
746 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
749 error = fo_add_seals(fp, arg);
754 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
757 if (fo_get_seals(fp, &seals) == 0)
758 td->td_retval[0] = seals;
765 arg = arg ? 128 * 1024: 0;
768 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
771 if (fp->f_type != DTYPE_VNODE) {
777 if (vp->v_type != VREG) {
784 * Exclusive lock synchronizes against f_seqcount reads and
785 * writes in sequential_heuristic().
787 error = vn_lock(vp, LK_EXCLUSIVE);
793 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
794 arg = MIN(arg, INT_MAX - bsize + 1);
795 fp->f_seqcount = MIN(IO_SEQMAX,
796 (arg + bsize - 1) / bsize);
797 atomic_set_int(&fp->f_flag, FRDAHEAD);
799 atomic_clear_int(&fp->f_flag, FRDAHEAD);
807 * Check if the vnode is part of a union stack (either the
808 * "union" flag from mount(2) or unionfs).
810 * Prior to introduction of this op libc's readdir would call
811 * fstatfs(2), in effect unnecessarily copying kilobytes of
812 * data just to check fs name and a mount flag.
814 * Fixing the code to handle everything in the kernel instead
815 * is a non-trivial endeavor and has low priority, thus this
816 * horrible kludge facilitates the current behavior in a much
817 * cheaper manner until someone(tm) sorts this out.
819 error = fget_unlocked(fdp, fd, &cap_no_rights, &fp);
822 if (fp->f_type != DTYPE_VNODE) {
829 * Since we don't prevent dooming the vnode even non-null mp
830 * found can become immediately stale. This is tolerable since
831 * mount points are type-stable (providing safe memory access)
832 * and any vfs op on this vnode going forward will return an
833 * error (meaning return value in this case is meaningless).
835 mp = atomic_load_ptr(&vp->v_mount);
836 if (__predict_false(mp == NULL)) {
841 td->td_retval[0] = 0;
842 if (mp->mnt_kern_flag & MNTK_UNIONFS ||
843 mp->mnt_flag & MNT_UNION)
844 td->td_retval[0] = 1;
856 getmaxfd(struct thread *td)
859 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
863 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
866 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
868 struct filedesc *fdp;
869 struct filedescent *oldfde, *newfde;
872 u_long *oioctls, *nioctls;
879 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
880 MPASS(mode < FDDUP_LASTMODE);
883 /* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
886 * Verify we have a valid descriptor to dup from and possibly to
887 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
888 * return EINVAL when the new descriptor is out of bounds.
893 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
894 maxfd = getmaxfd(td);
896 return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
900 if (fget_locked(fdp, old) == NULL)
902 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) {
903 td->td_retval[0] = new;
904 if (flags & FDDUP_FLAG_CLOEXEC)
905 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
910 oldfde = &fdp->fd_ofiles[old];
911 if (!fhold(oldfde->fde_file))
915 * If the caller specified a file descriptor, make sure the file
916 * table is large enough to hold it, and grab it. Otherwise, just
917 * allocate a new descriptor the usual way.
922 if ((error = fdalloc(td, new, &new)) != 0) {
923 fdrop(oldfde->fde_file, td);
927 case FDDUP_MUSTREPLACE:
928 /* Target file descriptor must exist. */
929 if (fget_locked(fdp, new) == NULL) {
930 fdrop(oldfde->fde_file, td);
935 if (new >= fdp->fd_nfiles) {
937 * The resource limits are here instead of e.g.
938 * fdalloc(), because the file descriptor table may be
939 * shared between processes, so we can't really use
940 * racct_add()/racct_sub(). Instead of counting the
941 * number of actually allocated descriptors, just put
942 * the limit on the size of the file descriptor table.
945 if (RACCT_ENABLED()) {
946 error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
949 fdrop(oldfde->fde_file, td);
954 fdgrowtable_exp(fdp, new + 1);
956 if (!fdisused(fdp, new))
960 KASSERT(0, ("%s unsupported mode %d", __func__, mode));
963 KASSERT(old != new, ("new fd is same as old"));
965 newfde = &fdp->fd_ofiles[new];
966 delfp = newfde->fde_file;
968 oioctls = filecaps_free_prep(&newfde->fde_caps);
969 nioctls = filecaps_copy_prep(&oldfde->fde_caps);
972 * Duplicate the source descriptor.
975 seqc_write_begin(&newfde->fde_seqc);
977 memcpy(newfde, oldfde, fde_change_size);
978 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
980 if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
981 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
983 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
985 seqc_write_end(&newfde->fde_seqc);
987 td->td_retval[0] = new;
992 (void) closefp(fdp, new, delfp, td, 1);
993 FILEDESC_UNLOCK_ASSERT(fdp);
996 FILEDESC_XUNLOCK(fdp);
999 filecaps_free_finish(oioctls);
1004 * If sigio is on the list associated with a process or process group,
1005 * disable signalling from the device, remove sigio from the list and
1009 funsetown(struct sigio **sigiop)
1011 struct sigio *sigio;
1013 if (*sigiop == NULL)
1017 if (sigio == NULL) {
1021 *(sigio->sio_myref) = NULL;
1022 if ((sigio)->sio_pgid < 0) {
1023 struct pgrp *pg = (sigio)->sio_pgrp;
1025 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1026 sigio, sio_pgsigio);
1029 struct proc *p = (sigio)->sio_proc;
1031 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1032 sigio, sio_pgsigio);
1036 crfree(sigio->sio_ucred);
1037 free(sigio, M_SIGIO);
1041 * Free a list of sigio structures.
1042 * We only need to lock the SIGIO_LOCK because we have made ourselves
1043 * inaccessible to callers of fsetown and therefore do not need to lock
1044 * the proc or pgrp struct for the list manipulation.
1047 funsetownlst(struct sigiolst *sigiolst)
1051 struct sigio *sigio;
1053 sigio = SLIST_FIRST(sigiolst);
1060 * Every entry of the list should belong
1061 * to a single proc or pgrp.
1063 if (sigio->sio_pgid < 0) {
1064 pg = sigio->sio_pgrp;
1065 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1066 } else /* if (sigio->sio_pgid > 0) */ {
1067 p = sigio->sio_proc;
1068 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1072 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1073 *(sigio->sio_myref) = NULL;
1075 KASSERT(sigio->sio_pgid < 0,
1076 ("Proc sigio in pgrp sigio list"));
1077 KASSERT(sigio->sio_pgrp == pg,
1078 ("Bogus pgrp in sigio list"));
1080 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1083 } else /* if (p != NULL) */ {
1084 KASSERT(sigio->sio_pgid > 0,
1085 ("Pgrp sigio in proc sigio list"));
1086 KASSERT(sigio->sio_proc == p,
1087 ("Bogus proc in sigio list"));
1089 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1094 crfree(sigio->sio_ucred);
1095 free(sigio, M_SIGIO);
1102 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1104 * After permission checking, add a sigio structure to the sigio list for
1105 * the process or process group.
1108 fsetown(pid_t pgid, struct sigio **sigiop)
1112 struct sigio *sigio;
1122 /* Allocate and fill in the new sigio out of locks. */
1123 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1124 sigio->sio_pgid = pgid;
1125 sigio->sio_ucred = crhold(curthread->td_ucred);
1126 sigio->sio_myref = sigiop;
1128 sx_slock(&proctree_lock);
1137 * Policy - Don't allow a process to FSETOWN a process
1138 * in another session.
1140 * Remove this test to allow maximum flexibility or
1141 * restrict FSETOWN to the current process or process
1142 * group for maximum safety.
1145 if (proc->p_session != curthread->td_proc->p_session) {
1151 } else /* if (pgid < 0) */ {
1152 pgrp = pgfind(-pgid);
1160 * Policy - Don't allow a process to FSETOWN a process
1161 * in another session.
1163 * Remove this test to allow maximum flexibility or
1164 * restrict FSETOWN to the current process or process
1165 * group for maximum safety.
1167 if (pgrp->pg_session != curthread->td_proc->p_session) {
1178 * Since funsetownlst() is called without the proctree
1179 * locked, we need to check for P_WEXIT.
1180 * XXX: is ESRCH correct?
1182 if ((proc->p_flag & P_WEXIT) != 0) {
1187 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1188 sigio->sio_proc = proc;
1192 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1193 sigio->sio_pgrp = pgrp;
1196 sx_sunlock(&proctree_lock);
1203 sx_sunlock(&proctree_lock);
1204 crfree(sigio->sio_ucred);
1205 free(sigio, M_SIGIO);
1210 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1213 fgetown(struct sigio **sigiop)
1218 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1224 * Function drops the filedesc lock on return.
1227 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1232 FILEDESC_XLOCK_ASSERT(fdp);
1235 if (td->td_proc->p_fdtol != NULL) {
1237 * Ask fdfree() to sleep to ensure that all relevant
1238 * process leaders can be traversed in closef().
1240 fdp->fd_holdleaderscount++;
1247 * We now hold the fp reference that used to be owned by the
1248 * descriptor array. We have to unlock the FILEDESC *AFTER*
1249 * knote_fdclose to prevent a race of the fd getting opened, a knote
1250 * added, and deleteing a knote for the new fd.
1252 if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1253 knote_fdclose(td, fd);
1256 * We need to notify mqueue if the object is of type mqueue.
1258 if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1259 mq_fdclose(td, fd, fp);
1260 FILEDESC_XUNLOCK(fdp);
1262 error = closef(fp, td);
1264 FILEDESC_XLOCK(fdp);
1265 fdp->fd_holdleaderscount--;
1266 if (fdp->fd_holdleaderscount == 0 &&
1267 fdp->fd_holdleaderswakeup != 0) {
1268 fdp->fd_holdleaderswakeup = 0;
1269 wakeup(&fdp->fd_holdleaderscount);
1271 FILEDESC_XUNLOCK(fdp);
1277 * Close a file descriptor.
1279 #ifndef _SYS_SYSPROTO_H_
1286 sys_close(struct thread *td, struct close_args *uap)
1289 return (kern_close(td, uap->fd));
1293 kern_close(struct thread *td, int fd)
1295 struct filedesc *fdp;
1298 fdp = td->td_proc->p_fd;
1300 AUDIT_SYSCLOSE(td, fd);
1302 FILEDESC_XLOCK(fdp);
1303 if ((fp = fget_locked(fdp, fd)) == NULL) {
1304 FILEDESC_XUNLOCK(fdp);
1309 /* closefp() drops the FILEDESC lock for us. */
1310 return (closefp(fdp, fd, fp, td, 1));
1314 * Close open file descriptors.
1316 #ifndef _SYS_SYSPROTO_H_
1317 struct closefrom_args {
1323 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1325 struct filedesc *fdp;
1328 fdp = td->td_proc->p_fd;
1329 AUDIT_ARG_FD(uap->lowfd);
1332 * Treat negative starting file descriptor values identical to
1333 * closefrom(0) which closes all files.
1337 FILEDESC_SLOCK(fdp);
1338 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1339 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1340 FILEDESC_SUNLOCK(fdp);
1341 (void)kern_close(td, fd);
1342 FILEDESC_SLOCK(fdp);
1345 FILEDESC_SUNLOCK(fdp);
1349 #if defined(COMPAT_43)
1351 * Return status information about a file descriptor.
1353 #ifndef _SYS_SYSPROTO_H_
1354 struct ofstat_args {
1361 ofstat(struct thread *td, struct ofstat_args *uap)
1367 error = kern_fstat(td, uap->fd, &ub);
1370 error = copyout(&oub, uap->sb, sizeof(oub));
1374 #endif /* COMPAT_43 */
1376 #if defined(COMPAT_FREEBSD11)
1378 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1381 struct freebsd11_stat osb;
1384 error = kern_fstat(td, uap->fd, &sb);
1387 error = freebsd11_cvtstat(&sb, &osb);
1389 error = copyout(&osb, uap->sb, sizeof(osb));
1392 #endif /* COMPAT_FREEBSD11 */
1395 * Return status information about a file descriptor.
1397 #ifndef _SYS_SYSPROTO_H_
1405 sys_fstat(struct thread *td, struct fstat_args *uap)
1410 error = kern_fstat(td, uap->fd, &ub);
1412 error = copyout(&ub, uap->sb, sizeof(ub));
1417 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1424 error = fget(td, fd, &cap_fstat_rights, &fp);
1425 if (__predict_false(error != 0))
1428 AUDIT_ARG_FILE(td->td_proc, fp);
1430 error = fo_stat(fp, sbp, td->td_ucred, td);
1432 #ifdef __STAT_TIME_T_EXT
1433 sbp->st_atim_ext = 0;
1434 sbp->st_mtim_ext = 0;
1435 sbp->st_ctim_ext = 0;
1436 sbp->st_btim_ext = 0;
1439 if (KTRPOINT(td, KTR_STRUCT))
1440 ktrstat_error(sbp, error);
1445 #if defined(COMPAT_FREEBSD11)
1447 * Return status information about a file descriptor.
1449 #ifndef _SYS_SYSPROTO_H_
1450 struct freebsd11_nfstat_args {
1457 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1463 error = kern_fstat(td, uap->fd, &ub);
1465 freebsd11_cvtnstat(&ub, &nub);
1466 error = copyout(&nub, uap->sb, sizeof(nub));
1470 #endif /* COMPAT_FREEBSD11 */
1473 * Return pathconf information about a file descriptor.
1475 #ifndef _SYS_SYSPROTO_H_
1476 struct fpathconf_args {
1483 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1488 error = kern_fpathconf(td, uap->fd, uap->name, &value);
1490 td->td_retval[0] = value;
1495 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1501 error = fget(td, fd, &cap_fpathconf_rights, &fp);
1505 if (name == _PC_ASYNC_IO) {
1506 *valuep = _POSIX_ASYNCHRONOUS_IO;
1511 vn_lock(vp, LK_SHARED | LK_RETRY);
1512 error = VOP_PATHCONF(vp, name, valuep);
1514 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1515 if (name != _PC_PIPE_BUF) {
1530 * Copy filecaps structure allocating memory for ioctls array if needed.
1532 * The last parameter indicates whether the fdtable is locked. If it is not and
1533 * ioctls are encountered, copying fails and the caller must lock the table.
1535 * Note that if the table was not locked, the caller has to check the relevant
1536 * sequence counter to determine whether the operation was successful.
1539 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1543 if (src->fc_ioctls != NULL && !locked)
1545 memcpy(dst, src, sizeof(*src));
1546 if (src->fc_ioctls == NULL)
1549 KASSERT(src->fc_nioctls > 0,
1550 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1552 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1553 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1554 memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1559 filecaps_copy_prep(const struct filecaps *src)
1564 if (__predict_true(src->fc_ioctls == NULL))
1567 KASSERT(src->fc_nioctls > 0,
1568 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1570 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1571 ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1576 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1582 if (__predict_true(src->fc_ioctls == NULL)) {
1583 MPASS(ioctls == NULL);
1587 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1588 dst->fc_ioctls = ioctls;
1589 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1593 * Move filecaps structure to the new place and clear the old place.
1596 filecaps_move(struct filecaps *src, struct filecaps *dst)
1600 bzero(src, sizeof(*src));
1604 * Fill the given filecaps structure with full rights.
1607 filecaps_fill(struct filecaps *fcaps)
1610 CAP_ALL(&fcaps->fc_rights);
1611 fcaps->fc_ioctls = NULL;
1612 fcaps->fc_nioctls = -1;
1613 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1617 * Free memory allocated within filecaps structure.
1620 filecaps_free(struct filecaps *fcaps)
1623 free(fcaps->fc_ioctls, M_FILECAPS);
1624 bzero(fcaps, sizeof(*fcaps));
1628 filecaps_free_prep(struct filecaps *fcaps)
1632 ioctls = fcaps->fc_ioctls;
1633 bzero(fcaps, sizeof(*fcaps));
1638 filecaps_free_finish(u_long *ioctls)
1641 free(ioctls, M_FILECAPS);
1645 * Validate the given filecaps structure.
1648 filecaps_validate(const struct filecaps *fcaps, const char *func)
1651 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1652 ("%s: invalid rights", func));
1653 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1654 ("%s: invalid fcntls", func));
1655 KASSERT(fcaps->fc_fcntls == 0 ||
1656 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1657 ("%s: fcntls without CAP_FCNTL", func));
1658 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1659 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1660 ("%s: invalid ioctls", func));
1661 KASSERT(fcaps->fc_nioctls == 0 ||
1662 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1663 ("%s: ioctls without CAP_IOCTL", func));
1667 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1671 FILEDESC_XLOCK_ASSERT(fdp);
1673 nfd1 = fdp->fd_nfiles * 2;
1676 fdgrowtable(fdp, nfd1);
1680 * Grow the file table to accommodate (at least) nfd descriptors.
1683 fdgrowtable(struct filedesc *fdp, int nfd)
1685 struct filedesc0 *fdp0;
1686 struct freetable *ft;
1687 struct fdescenttbl *ntable;
1688 struct fdescenttbl *otable;
1689 int nnfiles, onfiles;
1690 NDSLOTTYPE *nmap, *omap;
1693 * If lastfile is -1 this struct filedesc was just allocated and we are
1694 * growing it to accommodate for the one we are going to copy from. There
1695 * is no need to have a lock on this one as it's not visible to anyone.
1697 if (fdp->fd_lastfile != -1)
1698 FILEDESC_XLOCK_ASSERT(fdp);
1700 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1702 /* save old values */
1703 onfiles = fdp->fd_nfiles;
1704 otable = fdp->fd_files;
1707 /* compute the size of the new table */
1708 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1709 if (nnfiles <= onfiles)
1710 /* the table is already large enough */
1714 * Allocate a new table. We need enough space for the number of
1715 * entries, file entries themselves and the struct freetable we will use
1716 * when we decommission the table and place it on the freelist.
1717 * We place the struct freetable in the middle so we don't have
1718 * to worry about padding.
1720 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1721 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1722 sizeof(struct freetable),
1723 M_FILEDESC, M_ZERO | M_WAITOK);
1724 /* copy the old data */
1725 ntable->fdt_nfiles = nnfiles;
1726 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1727 onfiles * sizeof(ntable->fdt_ofiles[0]));
1730 * Allocate a new map only if the old is not large enough. It will
1731 * grow at a slower rate than the table as it can map more
1732 * entries than the table can hold.
1734 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1735 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1737 /* copy over the old data and update the pointer */
1738 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1743 * Make sure that ntable is correctly initialized before we replace
1744 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1747 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1750 * Do not free the old file table, as some threads may still
1751 * reference entries within it. Instead, place it on a freelist
1752 * which will be processed when the struct filedesc is released.
1754 * Note that if onfiles == NDFILE, we're dealing with the original
1755 * static allocation contained within (struct filedesc0 *)fdp,
1756 * which must not be freed.
1758 if (onfiles > NDFILE) {
1759 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1760 fdp0 = (struct filedesc0 *)fdp;
1761 ft->ft_table = otable;
1762 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1765 * The map does not have the same possibility of threads still
1766 * holding references to it. So always free it as long as it
1767 * does not reference the original static allocation.
1769 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1770 free(omap, M_FILEDESC);
1774 * Allocate a file descriptor for the process.
1777 fdalloc(struct thread *td, int minfd, int *result)
1779 struct proc *p = td->td_proc;
1780 struct filedesc *fdp = p->p_fd;
1781 int fd, maxfd, allocfd;
1786 FILEDESC_XLOCK_ASSERT(fdp);
1788 if (fdp->fd_freefile > minfd)
1789 minfd = fdp->fd_freefile;
1791 maxfd = getmaxfd(td);
1794 * Search the bitmap for a free descriptor starting at minfd.
1795 * If none is found, grow the file table.
1797 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1800 if (fd >= fdp->fd_nfiles) {
1801 allocfd = min(fd * 2, maxfd);
1803 if (RACCT_ENABLED()) {
1804 error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
1810 * fd is already equal to first free descriptor >= minfd, so
1811 * we only need to grow the table and we are done.
1813 fdgrowtable_exp(fdp, allocfd);
1817 * Perform some sanity checks, then mark the file descriptor as
1818 * used and return it to the caller.
1820 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1821 ("invalid descriptor %d", fd));
1822 KASSERT(!fdisused(fdp, fd),
1823 ("fd_first_free() returned non-free descriptor"));
1824 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1825 ("file descriptor isn't free"));
1832 * Allocate n file descriptors for the process.
1835 fdallocn(struct thread *td, int minfd, int *fds, int n)
1837 struct proc *p = td->td_proc;
1838 struct filedesc *fdp = p->p_fd;
1841 FILEDESC_XLOCK_ASSERT(fdp);
1843 for (i = 0; i < n; i++)
1844 if (fdalloc(td, 0, &fds[i]) != 0)
1848 for (i--; i >= 0; i--)
1849 fdunused(fdp, fds[i]);
1857 * Create a new open file structure and allocate a file descriptor for the
1858 * process that refers to it. We add one reference to the file for the
1859 * descriptor table and one reference for resultfp. This is to prevent us
1860 * being preempted and the entry in the descriptor table closed after we
1861 * release the FILEDESC lock.
1864 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
1865 struct filecaps *fcaps)
1870 error = falloc_noinstall(td, &fp);
1872 return (error); /* no reference held on error */
1874 error = finstall(td, fp, &fd, flags, fcaps);
1876 fdrop(fp, td); /* one reference (fp only) */
1880 if (resultfp != NULL)
1881 *resultfp = fp; /* copy out result */
1883 fdrop(fp, td); /* release local reference */
1885 if (resultfd != NULL)
1892 * Create a new open file structure without allocating a file descriptor.
1895 falloc_noinstall(struct thread *td, struct file **resultfp)
1898 int maxuserfiles = maxfiles - (maxfiles / 20);
1900 static struct timeval lastfail;
1903 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1905 openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
1906 if ((openfiles_new >= maxuserfiles &&
1907 priv_check(td, PRIV_MAXFILES) != 0) ||
1908 openfiles_new >= maxfiles) {
1909 atomic_subtract_int(&openfiles, 1);
1910 if (ppsratecheck(&lastfail, &curfail, 1)) {
1911 printf("kern.maxfiles limit exceeded by uid %i, (%s) "
1912 "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
1916 fp = uma_zalloc(file_zone, M_WAITOK);
1917 bzero(fp, sizeof(*fp));
1918 refcount_init(&fp->f_count, 1);
1919 fp->f_cred = crhold(td->td_ucred);
1920 fp->f_ops = &badfileops;
1926 * Install a file in a file descriptor table.
1929 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1930 struct filecaps *fcaps)
1932 struct filedescent *fde;
1936 filecaps_validate(fcaps, __func__);
1937 FILEDESC_XLOCK_ASSERT(fdp);
1939 fde = &fdp->fd_ofiles[fd];
1941 seqc_write_begin(&fde->fde_seqc);
1944 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1946 filecaps_move(fcaps, &fde->fde_caps);
1948 filecaps_fill(&fde->fde_caps);
1950 seqc_write_end(&fde->fde_seqc);
1955 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1956 struct filecaps *fcaps)
1958 struct filedesc *fdp = td->td_proc->p_fd;
1965 FILEDESC_XLOCK(fdp);
1966 error = fdalloc(td, 0, fd);
1967 if (__predict_false(error != 0)) {
1968 FILEDESC_XUNLOCK(fdp);
1972 _finstall(fdp, fp, *fd, flags, fcaps);
1973 FILEDESC_XUNLOCK(fdp);
1978 * Build a new filedesc structure from another.
1979 * Copy the current, root, and jail root vnode references.
1981 * If fdp is not NULL, return with it shared locked.
1984 fdinit(struct filedesc *fdp, bool prepfiles)
1986 struct filedesc0 *newfdp0;
1987 struct filedesc *newfdp;
1989 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1990 newfdp = &newfdp0->fd_fd;
1992 /* Create the file descriptor table. */
1993 FILEDESC_LOCK_INIT(newfdp);
1994 refcount_init(&newfdp->fd_refcnt, 1);
1995 refcount_init(&newfdp->fd_holdcnt, 1);
1996 newfdp->fd_cmask = CMASK;
1997 newfdp->fd_map = newfdp0->fd_dmap;
1998 newfdp->fd_lastfile = -1;
1999 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2000 newfdp->fd_files->fdt_nfiles = NDFILE;
2003 newfdp->fd_pwd = pwd_alloc();
2007 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
2008 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2010 FILEDESC_SLOCK(fdp);
2011 newfdp->fd_pwd = pwd_hold_filedesc(fdp);
2014 FILEDESC_SUNLOCK(fdp);
2016 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
2017 FILEDESC_SUNLOCK(fdp);
2018 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
2019 FILEDESC_SLOCK(fdp);
2026 static struct filedesc *
2027 fdhold(struct proc *p)
2029 struct filedesc *fdp;
2031 PROC_LOCK_ASSERT(p, MA_OWNED);
2034 refcount_acquire(&fdp->fd_holdcnt);
2039 fddrop(struct filedesc *fdp)
2042 if (fdp->fd_holdcnt > 1) {
2043 if (refcount_release(&fdp->fd_holdcnt) == 0)
2047 FILEDESC_LOCK_DESTROY(fdp);
2048 uma_zfree(filedesc0_zone, fdp);
2052 * Share a filedesc structure.
2055 fdshare(struct filedesc *fdp)
2058 refcount_acquire(&fdp->fd_refcnt);
2063 * Unshare a filedesc structure, if necessary by making a copy
2066 fdunshare(struct thread *td)
2068 struct filedesc *tmp;
2069 struct proc *p = td->td_proc;
2071 if (p->p_fd->fd_refcnt == 1)
2074 tmp = fdcopy(p->p_fd);
2080 fdinstall_remapped(struct thread *td, struct filedesc *fdp)
2084 td->td_proc->p_fd = fdp;
2088 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
2089 * this is to ease callers, not catch errors.
2092 fdcopy(struct filedesc *fdp)
2094 struct filedesc *newfdp;
2095 struct filedescent *nfde, *ofde;
2100 newfdp = fdinit(fdp, true);
2101 /* copy all passable descriptors (i.e. not kqueue) */
2102 newfdp->fd_freefile = -1;
2103 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2104 ofde = &fdp->fd_ofiles[i];
2105 if (ofde->fde_file == NULL ||
2106 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2107 !fhold(ofde->fde_file)) {
2108 if (newfdp->fd_freefile == -1)
2109 newfdp->fd_freefile = i;
2112 nfde = &newfdp->fd_ofiles[i];
2114 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2115 fdused_init(newfdp, i);
2116 newfdp->fd_lastfile = i;
2118 if (newfdp->fd_freefile == -1)
2119 newfdp->fd_freefile = i;
2120 newfdp->fd_cmask = fdp->fd_cmask;
2121 FILEDESC_SUNLOCK(fdp);
2126 * Copies a filedesc structure, while remapping all file descriptors
2127 * stored inside using a translation table.
2129 * File descriptors are copied over to the new file descriptor table,
2130 * regardless of whether the close-on-exec flag is set.
2133 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds,
2134 struct filedesc **ret)
2136 struct filedesc *newfdp;
2137 struct filedescent *nfde, *ofde;
2142 newfdp = fdinit(fdp, true);
2143 if (nfds > fdp->fd_lastfile + 1) {
2144 /* New table cannot be larger than the old one. */
2148 /* Copy all passable descriptors (i.e. not kqueue). */
2149 newfdp->fd_freefile = nfds;
2150 for (i = 0; i < nfds; ++i) {
2151 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) {
2152 /* File descriptor out of bounds. */
2156 ofde = &fdp->fd_ofiles[fds[i]];
2157 if (ofde->fde_file == NULL) {
2158 /* Unused file descriptor. */
2162 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
2163 /* File descriptor cannot be passed. */
2167 if (!fhold(nfde->fde_file)) {
2171 nfde = &newfdp->fd_ofiles[i];
2173 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2174 fdused_init(newfdp, i);
2175 newfdp->fd_lastfile = i;
2177 newfdp->fd_cmask = fdp->fd_cmask;
2178 FILEDESC_SUNLOCK(fdp);
2182 FILEDESC_SUNLOCK(fdp);
2183 fdescfree_remapped(newfdp);
2188 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2189 * one of processes using it exits) and the table used to be shared.
2192 fdclearlocks(struct thread *td)
2194 struct filedesc *fdp;
2195 struct filedesc_to_leader *fdtol;
2205 MPASS(fdtol != NULL);
2207 FILEDESC_XLOCK(fdp);
2208 KASSERT(fdtol->fdl_refcount > 0,
2209 ("filedesc_to_refcount botch: fdl_refcount=%d",
2210 fdtol->fdl_refcount));
2211 if (fdtol->fdl_refcount == 1 &&
2212 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2213 for (i = 0; i <= fdp->fd_lastfile; i++) {
2214 fp = fdp->fd_ofiles[i].fde_file;
2215 if (fp == NULL || fp->f_type != DTYPE_VNODE ||
2218 FILEDESC_XUNLOCK(fdp);
2219 lf.l_whence = SEEK_SET;
2222 lf.l_type = F_UNLCK;
2224 (void) VOP_ADVLOCK(vp,
2225 (caddr_t)p->p_leader, F_UNLCK,
2227 FILEDESC_XLOCK(fdp);
2232 if (fdtol->fdl_refcount == 1) {
2233 if (fdp->fd_holdleaderscount > 0 &&
2234 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2236 * close() or kern_dup() has cleared a reference
2237 * in a shared file descriptor table.
2239 fdp->fd_holdleaderswakeup = 1;
2240 sx_sleep(&fdp->fd_holdleaderscount,
2241 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2244 if (fdtol->fdl_holdcount > 0) {
2246 * Ensure that fdtol->fdl_leader remains
2247 * valid in closef().
2249 fdtol->fdl_wakeup = 1;
2250 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2255 fdtol->fdl_refcount--;
2256 if (fdtol->fdl_refcount == 0 &&
2257 fdtol->fdl_holdcount == 0) {
2258 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2259 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2263 FILEDESC_XUNLOCK(fdp);
2265 free(fdtol, M_FILEDESC_TO_LEADER);
2269 * Release a filedesc structure.
2272 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose)
2274 struct filedesc0 *fdp0;
2275 struct freetable *ft, *tft;
2276 struct filedescent *fde;
2280 for (i = 0; i <= fdp->fd_lastfile; i++) {
2281 fde = &fdp->fd_ofiles[i];
2286 (void) closef(fp, td);
2292 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2293 free(fdp->fd_map, M_FILEDESC);
2294 if (fdp->fd_nfiles > NDFILE)
2295 free(fdp->fd_files, M_FILEDESC);
2297 fdp0 = (struct filedesc0 *)fdp;
2298 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2299 free(ft->ft_table, M_FILEDESC);
2305 fdescfree(struct thread *td)
2308 struct filedesc *fdp;
2316 if (RACCT_ENABLED())
2317 racct_set_unlocked(p, RACCT_NOFILE, 0);
2320 if (p->p_fdtol != NULL)
2327 if (refcount_release(&fdp->fd_refcnt) == 0)
2330 FILEDESC_XLOCK(fdp);
2333 FILEDESC_XUNLOCK(fdp);
2337 fdescfree_fds(td, fdp, 1);
2341 fdescfree_remapped(struct filedesc *fdp)
2344 pwd_drop(fdp->fd_pwd);
2345 fdescfree_fds(curthread, fdp, 0);
2349 * For setugid programs, we don't want to people to use that setugidness
2350 * to generate error messages which write to a file which otherwise would
2351 * otherwise be off-limits to the process. We check for filesystems where
2352 * the vnode can change out from under us after execve (like [lin]procfs).
2354 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2355 * sufficient. We also don't check for setugidness since we know we are.
2358 is_unsafe(struct file *fp)
2362 if (fp->f_type != DTYPE_VNODE)
2366 return ((vp->v_vflag & VV_PROCDEP) != 0);
2370 * Make this setguid thing safe, if at all possible.
2373 fdsetugidsafety(struct thread *td)
2375 struct filedesc *fdp;
2379 fdp = td->td_proc->p_fd;
2380 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2381 MPASS(fdp->fd_nfiles >= 3);
2382 for (i = 0; i <= 2; i++) {
2383 fp = fdp->fd_ofiles[i].fde_file;
2384 if (fp != NULL && is_unsafe(fp)) {
2385 FILEDESC_XLOCK(fdp);
2386 knote_fdclose(td, i);
2388 * NULL-out descriptor prior to close to avoid
2389 * a race while close blocks.
2392 FILEDESC_XUNLOCK(fdp);
2393 (void) closef(fp, td);
2399 * If a specific file object occupies a specific file descriptor, close the
2400 * file descriptor entry and drop a reference on the file object. This is a
2401 * convenience function to handle a subsequent error in a function that calls
2402 * falloc() that handles the race that another thread might have closed the
2403 * file descriptor out from under the thread creating the file object.
2406 fdclose(struct thread *td, struct file *fp, int idx)
2408 struct filedesc *fdp = td->td_proc->p_fd;
2410 FILEDESC_XLOCK(fdp);
2411 if (fdp->fd_ofiles[idx].fde_file == fp) {
2413 FILEDESC_XUNLOCK(fdp);
2416 FILEDESC_XUNLOCK(fdp);
2420 * Close any files on exec?
2423 fdcloseexec(struct thread *td)
2425 struct filedesc *fdp;
2426 struct filedescent *fde;
2430 fdp = td->td_proc->p_fd;
2431 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2432 for (i = 0; i <= fdp->fd_lastfile; i++) {
2433 fde = &fdp->fd_ofiles[i];
2435 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2436 (fde->fde_flags & UF_EXCLOSE))) {
2437 FILEDESC_XLOCK(fdp);
2439 (void) closefp(fdp, i, fp, td, 0);
2440 FILEDESC_UNLOCK_ASSERT(fdp);
2446 * It is unsafe for set[ug]id processes to be started with file
2447 * descriptors 0..2 closed, as these descriptors are given implicit
2448 * significance in the Standard C library. fdcheckstd() will create a
2449 * descriptor referencing /dev/null for each of stdin, stdout, and
2450 * stderr that is not already open.
2453 fdcheckstd(struct thread *td)
2455 struct filedesc *fdp;
2457 int i, error, devnull;
2459 fdp = td->td_proc->p_fd;
2460 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2461 MPASS(fdp->fd_nfiles >= 3);
2463 for (i = 0; i <= 2; i++) {
2464 if (fdp->fd_ofiles[i].fde_file != NULL)
2467 save = td->td_retval[0];
2468 if (devnull != -1) {
2469 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2471 error = kern_openat(td, AT_FDCWD, "/dev/null",
2472 UIO_SYSSPACE, O_RDWR, 0);
2474 devnull = td->td_retval[0];
2475 KASSERT(devnull == i, ("we didn't get our fd"));
2478 td->td_retval[0] = save;
2486 * Internal form of close. Decrement reference count on file structure.
2487 * Note: td may be NULL when closing a file that was being passed in a
2491 closef(struct file *fp, struct thread *td)
2495 struct filedesc_to_leader *fdtol;
2496 struct filedesc *fdp;
2499 * POSIX record locking dictates that any close releases ALL
2500 * locks owned by this process. This is handled by setting
2501 * a flag in the unlock to free ONLY locks obeying POSIX
2502 * semantics, and not to free BSD-style file locks.
2503 * If the descriptor was in a message, POSIX-style locks
2504 * aren't passed with the descriptor, and the thread pointer
2505 * will be NULL. Callers should be careful only to pass a
2506 * NULL thread pointer when there really is no owning
2507 * context that might have locks, or the locks will be
2510 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2512 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2513 lf.l_whence = SEEK_SET;
2516 lf.l_type = F_UNLCK;
2517 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2518 F_UNLCK, &lf, F_POSIX);
2520 fdtol = td->td_proc->p_fdtol;
2521 if (fdtol != NULL) {
2523 * Handle special case where file descriptor table is
2524 * shared between multiple process leaders.
2526 fdp = td->td_proc->p_fd;
2527 FILEDESC_XLOCK(fdp);
2528 for (fdtol = fdtol->fdl_next;
2529 fdtol != td->td_proc->p_fdtol;
2530 fdtol = fdtol->fdl_next) {
2531 if ((fdtol->fdl_leader->p_flag &
2534 fdtol->fdl_holdcount++;
2535 FILEDESC_XUNLOCK(fdp);
2536 lf.l_whence = SEEK_SET;
2539 lf.l_type = F_UNLCK;
2541 (void) VOP_ADVLOCK(vp,
2542 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2544 FILEDESC_XLOCK(fdp);
2545 fdtol->fdl_holdcount--;
2546 if (fdtol->fdl_holdcount == 0 &&
2547 fdtol->fdl_wakeup != 0) {
2548 fdtol->fdl_wakeup = 0;
2552 FILEDESC_XUNLOCK(fdp);
2555 return (fdrop(fp, td));
2559 * Initialize the file pointer with the specified properties.
2561 * The ops are set with release semantics to be certain that the flags, type,
2562 * and data are visible when ops is. This is to prevent ops methods from being
2563 * called with bad data.
2566 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2571 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2575 fget_cap_locked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2576 struct file **fpp, struct filecaps *havecapsp)
2578 struct filedescent *fde;
2581 FILEDESC_LOCK_ASSERT(fdp);
2583 fde = fdeget_locked(fdp, fd);
2590 error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2595 if (havecapsp != NULL)
2596 filecaps_copy(&fde->fde_caps, havecapsp, true);
2598 *fpp = fde->fde_file;
2606 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2607 struct file **fpp, struct filecaps *havecapsp)
2609 struct filedesc *fdp = td->td_proc->p_fd;
2611 #ifndef CAPABILITIES
2612 error = fget_unlocked(fdp, fd, needrightsp, fpp);
2613 if (havecapsp != NULL && error == 0)
2614 filecaps_fill(havecapsp);
2621 error = fget_unlocked_seq(fdp, fd, needrightsp, &fp, &seq);
2625 if (havecapsp != NULL) {
2626 if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2627 havecapsp, false)) {
2633 if (!fd_modified(fdp, fd, seq))
2642 FILEDESC_SLOCK(fdp);
2643 error = fget_cap_locked(fdp, fd, needrightsp, fpp, havecapsp);
2644 if (error == 0 && !fhold(*fpp))
2646 FILEDESC_SUNLOCK(fdp);
2652 fget_unlocked_seq(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2653 struct file **fpp, seqc_t *seqp)
2656 const struct filedescent *fde;
2658 const struct fdescenttbl *fdt;
2662 cap_rights_t haverights;
2666 fdt = fdp->fd_files;
2667 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2670 * Fetch the descriptor locklessly. We avoid fdrop() races by
2671 * never raising a refcount above 0. To accomplish this we have
2672 * to use a cmpset loop rather than an atomic_add. The descriptor
2673 * must be re-verified once we acquire a reference to be certain
2674 * that the identity is still correct and we did not lose a race
2675 * due to preemption.
2679 seq = seqc_read(fd_seqc(fdt, fd));
2680 fde = &fdt->fdt_ofiles[fd];
2681 haverights = *cap_rights_fde_inline(fde);
2683 if (!seqc_consistent(fd_seqc(fdt, fd), seq))
2686 fp = fdt->fdt_ofiles[fd].fde_file;
2691 error = cap_check_inline(&haverights, needrightsp);
2695 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
2697 * The count was found either saturated or zero.
2698 * This re-read is not any more racy than using the
2699 * return value from fcmpset.
2701 if (fp->f_count != 0)
2704 * Force a reload. Other thread could reallocate the
2705 * table before this fd was closed, so it is possible
2706 * that there is a stale fp pointer in cached version.
2708 fdt = atomic_load_ptr(&fdp->fd_files);
2712 * Use an acquire barrier to force re-reading of fdt so it is
2713 * refreshed for verification.
2715 atomic_thread_fence_acq();
2716 fdt = fdp->fd_files;
2718 if (seqc_consistent_nomb(fd_seqc(fdt, fd), seq))
2720 if (fp == fdt->fdt_ofiles[fd].fde_file)
2723 fdrop(fp, curthread);
2735 * See the comments in fget_unlocked_seq for an explanation of how this works.
2737 * This is a simplified variant which bails out to the aforementioned routine
2738 * if anything goes wrong. In practice this only happens when userspace is
2739 * racing with itself.
2742 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2746 const struct filedescent *fde;
2748 const struct fdescenttbl *fdt;
2752 const cap_rights_t *haverights;
2755 fdt = fdp->fd_files;
2756 if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
2759 seq = seqc_read_any(fd_seqc(fdt, fd));
2760 if (__predict_false(seqc_in_modify(seq)))
2762 fde = &fdt->fdt_ofiles[fd];
2763 haverights = cap_rights_fde_inline(fde);
2766 fp = fdt->fdt_ofiles[fd].fde_file;
2768 if (__predict_false(fp == NULL))
2771 if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
2774 if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
2778 * Use an acquire barrier to force re-reading of fdt so it is
2779 * refreshed for verification.
2781 atomic_thread_fence_acq();
2782 fdt = fdp->fd_files;
2784 if (__predict_false(!seqc_consistent_nomb(fd_seqc(fdt, fd), seq)))
2786 if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
2792 fdrop(fp, curthread);
2794 return (fget_unlocked_seq(fdp, fd, needrightsp, fpp, NULL));
2798 * Extract the file pointer associated with the specified descriptor for the
2799 * current user process.
2801 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2804 * File's rights will be checked against the capability rights mask.
2806 * If an error occurred the non-zero error is returned and *fpp is set to
2807 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2808 * responsible for fdrop().
2811 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2812 cap_rights_t *needrightsp)
2814 struct filedesc *fdp;
2819 fdp = td->td_proc->p_fd;
2820 error = fget_unlocked(fdp, fd, needrightsp, &fp);
2821 if (__predict_false(error != 0))
2823 if (__predict_false(fp->f_ops == &badfileops)) {
2829 * FREAD and FWRITE failure return EBADF as per POSIX.
2835 if ((fp->f_flag & flags) == 0)
2839 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2840 ((fp->f_flag & FWRITE) != 0))
2846 KASSERT(0, ("wrong flags"));
2859 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2862 return (_fget(td, fd, fpp, 0, rightsp));
2866 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
2870 #ifndef CAPABILITIES
2871 error = _fget(td, fd, fpp, 0, rightsp);
2872 if (maxprotp != NULL)
2873 *maxprotp = VM_PROT_ALL;
2876 cap_rights_t fdrights;
2877 struct filedesc *fdp;
2882 fdp = td->td_proc->p_fd;
2883 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2885 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2886 if (__predict_false(error != 0))
2888 if (__predict_false(fp->f_ops == &badfileops)) {
2892 if (maxprotp != NULL)
2893 fdrights = *cap_rights(fdp, fd);
2894 if (!fd_modified(fdp, fd, seq))
2900 * If requested, convert capability rights to access flags.
2902 if (maxprotp != NULL)
2903 *maxprotp = cap_rights_to_vmprot(&fdrights);
2910 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2913 return (_fget(td, fd, fpp, FREAD, rightsp));
2917 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2920 return (_fget(td, fd, fpp, FWRITE, rightsp));
2924 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2927 struct filedesc *fdp = td->td_proc->p_fd;
2928 #ifndef CAPABILITIES
2929 return (fget_unlocked(fdp, fd, rightsp, fpp));
2936 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2938 error = fget_unlocked_seq(fdp, fd, rightsp, &fp, &seq);
2941 error = cap_fcntl_check(fdp, fd, needfcntl);
2942 if (!fd_modified(fdp, fd, seq))
2956 * Like fget() but loads the underlying vnode, or returns an error if the
2957 * descriptor does not represent a vnode. Note that pipes use vnodes but
2958 * never have VM objects. The returned vnode will be vref()'d.
2960 * XXX: what about the unused flags ?
2963 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2970 error = _fget(td, fd, &fp, flags, needrightsp);
2973 if (fp->f_vnode == NULL) {
2985 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2988 return (_fgetvp(td, fd, 0, rightsp, vpp));
2992 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2993 struct filecaps *havecaps, struct vnode **vpp)
2995 struct filecaps caps;
2999 error = fget_cap(td, fd, needrightsp, &fp, &caps);
3002 if (fp->f_ops == &badfileops) {
3006 if (fp->f_vnode == NULL) {
3018 filecaps_free(&caps);
3024 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3027 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3031 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3034 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3039 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3043 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3048 * Handle the last reference to a file being closed.
3050 * Without the noinline attribute clang keeps inlining the func thorough this
3051 * file when fdrop is used.
3054 _fdrop(struct file *fp, struct thread *td)
3058 if (fp->f_count != 0)
3059 panic("fdrop: count %d", fp->f_count);
3060 error = fo_close(fp, td);
3061 atomic_subtract_int(&openfiles, 1);
3063 free(fp->f_advice, M_FADVISE);
3064 uma_zfree(file_zone, fp);
3070 * Apply an advisory lock on a file descriptor.
3072 * Just attempt to get a record lock of the requested type on the entire file
3073 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3075 #ifndef _SYS_SYSPROTO_H_
3083 sys_flock(struct thread *td, struct flock_args *uap)
3090 error = fget(td, uap->fd, &cap_flock_rights, &fp);
3093 if (fp->f_type != DTYPE_VNODE) {
3095 return (EOPNOTSUPP);
3099 lf.l_whence = SEEK_SET;
3102 if (uap->how & LOCK_UN) {
3103 lf.l_type = F_UNLCK;
3104 atomic_clear_int(&fp->f_flag, FHASLOCK);
3105 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3108 if (uap->how & LOCK_EX)
3109 lf.l_type = F_WRLCK;
3110 else if (uap->how & LOCK_SH)
3111 lf.l_type = F_RDLCK;
3116 atomic_set_int(&fp->f_flag, FHASLOCK);
3117 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3118 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3124 * Duplicate the specified descriptor to a free descriptor.
3127 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3128 int openerror, int *indxp)
3130 struct filedescent *newfde, *oldfde;
3135 KASSERT(openerror == ENODEV || openerror == ENXIO,
3136 ("unexpected error %d in %s", openerror, __func__));
3139 * If the to-be-dup'd fd number is greater than the allowed number
3140 * of file descriptors, or the fd to be dup'd has already been
3141 * closed, then reject.
3143 FILEDESC_XLOCK(fdp);
3144 if ((fp = fget_locked(fdp, dfd)) == NULL) {
3145 FILEDESC_XUNLOCK(fdp);
3149 error = fdalloc(td, 0, &indx);
3151 FILEDESC_XUNLOCK(fdp);
3156 * There are two cases of interest here.
3158 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3160 * For ENXIO steal away the file structure from (dfd) and store it in
3161 * (indx). (dfd) is effectively closed by this operation.
3163 switch (openerror) {
3166 * Check that the mode the file is being opened for is a
3167 * subset of the mode of the existing descriptor.
3169 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3170 fdunused(fdp, indx);
3171 FILEDESC_XUNLOCK(fdp);
3175 fdunused(fdp, indx);
3176 FILEDESC_XUNLOCK(fdp);
3179 newfde = &fdp->fd_ofiles[indx];
3180 oldfde = &fdp->fd_ofiles[dfd];
3181 ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3183 seqc_write_begin(&newfde->fde_seqc);
3185 memcpy(newfde, oldfde, fde_change_size);
3186 filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3189 seqc_write_end(&newfde->fde_seqc);
3194 * Steal away the file pointer from dfd and stuff it into indx.
3196 newfde = &fdp->fd_ofiles[indx];
3197 oldfde = &fdp->fd_ofiles[dfd];
3199 seqc_write_begin(&newfde->fde_seqc);
3201 memcpy(newfde, oldfde, fde_change_size);
3202 oldfde->fde_file = NULL;
3205 seqc_write_end(&newfde->fde_seqc);
3209 FILEDESC_XUNLOCK(fdp);
3215 * This sysctl determines if we will allow a process to chroot(2) if it
3216 * has a directory open:
3217 * 0: disallowed for all processes.
3218 * 1: allowed for processes that were not already chroot(2)'ed.
3219 * 2: allowed for all processes.
3222 static int chroot_allow_open_directories = 1;
3224 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3225 &chroot_allow_open_directories, 0,
3226 "Allow a process to chroot(2) if it has a directory open");
3229 * Helper function for raised chroot(2) security function: Refuse if
3230 * any filedescriptors are open directories.
3233 chroot_refuse_vdir_fds(struct filedesc *fdp)
3239 FILEDESC_LOCK_ASSERT(fdp);
3241 for (fd = 0; fd <= fdp->fd_lastfile; fd++) {
3242 fp = fget_locked(fdp, fd);
3245 if (fp->f_type == DTYPE_VNODE) {
3247 if (vp->v_type == VDIR)
3255 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3258 if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3259 vrefact(oldpwd->pwd_cdir);
3260 newpwd->pwd_cdir = oldpwd->pwd_cdir;
3263 if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3264 vrefact(oldpwd->pwd_rdir);
3265 newpwd->pwd_rdir = oldpwd->pwd_rdir;
3268 if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3269 vrefact(oldpwd->pwd_jdir);
3270 newpwd->pwd_jdir = oldpwd->pwd_jdir;
3275 pwd_hold_filedesc(struct filedesc *fdp)
3279 FILEDESC_LOCK_ASSERT(fdp);
3282 refcount_acquire(&pwd->pwd_refcount);
3287 pwd_hold(struct thread *td)
3289 struct filedesc *fdp;
3292 fdp = td->td_proc->p_fd;
3294 FILEDESC_SLOCK(fdp);
3297 refcount_acquire(&pwd->pwd_refcount);
3298 FILEDESC_SUNLOCK(fdp);
3307 pwd = malloc(sizeof(*pwd), M_PWD, M_WAITOK | M_ZERO);
3308 refcount_init(&pwd->pwd_refcount, 1);
3313 pwd_drop(struct pwd *pwd)
3316 if (!refcount_release(&pwd->pwd_refcount))
3319 if (pwd->pwd_cdir != NULL)
3320 vrele(pwd->pwd_cdir);
3321 if (pwd->pwd_rdir != NULL)
3322 vrele(pwd->pwd_rdir);
3323 if (pwd->pwd_jdir != NULL)
3324 vrele(pwd->pwd_jdir);
3329 * Common routine for kern_chroot() and jail_attach(). The caller is
3330 * responsible for invoking priv_check() and mac_vnode_check_chroot() to
3331 * authorize this operation.
3334 pwd_chroot(struct thread *td, struct vnode *vp)
3336 struct filedesc *fdp;
3337 struct pwd *newpwd, *oldpwd;
3340 fdp = td->td_proc->p_fd;
3341 newpwd = pwd_alloc();
3342 FILEDESC_XLOCK(fdp);
3343 oldpwd = fdp->fd_pwd;
3344 if (chroot_allow_open_directories == 0 ||
3345 (chroot_allow_open_directories == 1 &&
3346 oldpwd->pwd_rdir != rootvnode)) {
3347 error = chroot_refuse_vdir_fds(fdp);
3349 FILEDESC_XUNLOCK(fdp);
3356 newpwd->pwd_rdir = vp;
3357 if (oldpwd->pwd_jdir == NULL) {
3359 newpwd->pwd_jdir = vp;
3361 pwd_fill(oldpwd, newpwd);
3362 pwd_set(fdp, newpwd);
3363 FILEDESC_XUNLOCK(fdp);
3369 pwd_chdir(struct thread *td, struct vnode *vp)
3371 struct filedesc *fdp;
3372 struct pwd *newpwd, *oldpwd;
3374 VNPASS(vp->v_usecount > 0, vp);
3376 newpwd = pwd_alloc();
3377 fdp = td->td_proc->p_fd;
3378 FILEDESC_XLOCK(fdp);
3379 oldpwd = fdp->fd_pwd;
3380 newpwd->pwd_cdir = vp;
3381 pwd_fill(oldpwd, newpwd);
3382 pwd_set(fdp, newpwd);
3383 FILEDESC_XUNLOCK(fdp);
3388 pwd_ensure_dirs(void)
3390 struct filedesc *fdp;
3391 struct pwd *oldpwd, *newpwd;
3393 fdp = curproc->p_fd;
3394 FILEDESC_XLOCK(fdp);
3395 oldpwd = fdp->fd_pwd;
3396 if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL) {
3397 FILEDESC_XUNLOCK(fdp);
3400 FILEDESC_XUNLOCK(fdp);
3402 newpwd = pwd_alloc();
3403 FILEDESC_XLOCK(fdp);
3404 oldpwd = fdp->fd_pwd;
3405 pwd_fill(oldpwd, newpwd);
3406 if (newpwd->pwd_cdir == NULL) {
3408 newpwd->pwd_cdir = rootvnode;
3410 if (newpwd->pwd_rdir == NULL) {
3412 newpwd->pwd_rdir = rootvnode;
3414 pwd_set(fdp, newpwd);
3415 FILEDESC_XUNLOCK(fdp);
3420 * Scan all active processes and prisons to see if any of them have a current
3421 * or root directory of `olddp'. If so, replace them with the new mount point.
3424 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
3426 struct filedesc *fdp;
3427 struct pwd *newpwd, *oldpwd;
3432 if (vrefcnt(olddp) == 1)
3435 newpwd = pwd_alloc();
3436 sx_slock(&allproc_lock);
3437 FOREACH_PROC_IN_SYSTEM(p) {
3443 FILEDESC_XLOCK(fdp);
3444 oldpwd = fdp->fd_pwd;
3445 if (oldpwd == NULL ||
3446 (oldpwd->pwd_cdir != olddp &&
3447 oldpwd->pwd_rdir != olddp &&
3448 oldpwd->pwd_jdir != olddp)) {
3449 FILEDESC_XUNLOCK(fdp);
3453 if (oldpwd->pwd_cdir == olddp) {
3455 newpwd->pwd_cdir = newdp;
3457 if (oldpwd->pwd_rdir == olddp) {
3459 newpwd->pwd_rdir = newdp;
3461 if (oldpwd->pwd_jdir == olddp) {
3463 newpwd->pwd_jdir = newdp;
3465 pwd_fill(oldpwd, newpwd);
3466 pwd_set(fdp, newpwd);
3467 FILEDESC_XUNLOCK(fdp);
3470 newpwd = pwd_alloc();
3472 sx_sunlock(&allproc_lock);
3474 if (rootvnode == olddp) {
3479 mtx_lock(&prison0.pr_mtx);
3480 if (prison0.pr_root == olddp) {
3482 prison0.pr_root = newdp;
3485 mtx_unlock(&prison0.pr_mtx);
3486 sx_slock(&allprison_lock);
3487 TAILQ_FOREACH(pr, &allprison, pr_list) {
3488 mtx_lock(&pr->pr_mtx);
3489 if (pr->pr_root == olddp) {
3491 pr->pr_root = newdp;
3494 mtx_unlock(&pr->pr_mtx);
3496 sx_sunlock(&allprison_lock);
3501 struct filedesc_to_leader *
3502 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
3504 struct filedesc_to_leader *fdtol;
3506 fdtol = malloc(sizeof(struct filedesc_to_leader),
3507 M_FILEDESC_TO_LEADER, M_WAITOK);
3508 fdtol->fdl_refcount = 1;
3509 fdtol->fdl_holdcount = 0;
3510 fdtol->fdl_wakeup = 0;
3511 fdtol->fdl_leader = leader;
3513 FILEDESC_XLOCK(fdp);
3514 fdtol->fdl_next = old->fdl_next;
3515 fdtol->fdl_prev = old;
3516 old->fdl_next = fdtol;
3517 fdtol->fdl_next->fdl_prev = fdtol;
3518 FILEDESC_XUNLOCK(fdp);
3520 fdtol->fdl_next = fdtol;
3521 fdtol->fdl_prev = fdtol;
3527 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
3529 struct filedesc *fdp;
3530 int i, count, slots;
3532 if (*(int *)arg1 != 0)
3535 fdp = curproc->p_fd;
3537 FILEDESC_SLOCK(fdp);
3538 slots = NDSLOTS(fdp->fd_lastfile + 1);
3539 for (i = 0; i < slots; i++)
3540 count += bitcountl(fdp->fd_map[i]);
3541 FILEDESC_SUNLOCK(fdp);
3543 return (SYSCTL_OUT(req, &count, sizeof(count)));
3546 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
3547 CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
3548 "Number of open file descriptors");
3551 * Get file structures globally.
3554 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3557 struct filedesc *fdp;
3562 error = sysctl_wire_old_buffer(req, 0);
3565 if (req->oldptr == NULL) {
3567 sx_slock(&allproc_lock);
3568 FOREACH_PROC_IN_SYSTEM(p) {
3570 if (p->p_state == PRS_NEW) {
3578 /* overestimates sparse tables. */
3579 if (fdp->fd_lastfile > 0)
3580 n += fdp->fd_lastfile;
3583 sx_sunlock(&allproc_lock);
3584 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
3587 bzero(&xf, sizeof(xf));
3588 xf.xf_size = sizeof(xf);
3589 sx_slock(&allproc_lock);
3590 FOREACH_PROC_IN_SYSTEM(p) {
3592 if (p->p_state == PRS_NEW) {
3596 if (p_cansee(req->td, p) != 0) {
3600 xf.xf_pid = p->p_pid;
3601 xf.xf_uid = p->p_ucred->cr_uid;
3606 FILEDESC_SLOCK(fdp);
3607 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3608 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3611 xf.xf_file = (uintptr_t)fp;
3612 xf.xf_data = (uintptr_t)fp->f_data;
3613 xf.xf_vnode = (uintptr_t)fp->f_vnode;
3614 xf.xf_type = (uintptr_t)fp->f_type;
3615 xf.xf_count = fp->f_count;
3617 xf.xf_offset = foffset_get(fp);
3618 xf.xf_flag = fp->f_flag;
3619 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3623 FILEDESC_SUNLOCK(fdp);
3628 sx_sunlock(&allproc_lock);
3632 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3633 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3635 #ifdef KINFO_FILE_SIZE
3636 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3640 xlate_fflags(int fflags)
3642 static const struct {
3645 } fflags_table[] = {
3646 { FAPPEND, KF_FLAG_APPEND },
3647 { FASYNC, KF_FLAG_ASYNC },
3648 { FFSYNC, KF_FLAG_FSYNC },
3649 { FHASLOCK, KF_FLAG_HASLOCK },
3650 { FNONBLOCK, KF_FLAG_NONBLOCK },
3651 { FREAD, KF_FLAG_READ },
3652 { FWRITE, KF_FLAG_WRITE },
3653 { O_CREAT, KF_FLAG_CREAT },
3654 { O_DIRECT, KF_FLAG_DIRECT },
3655 { O_EXCL, KF_FLAG_EXCL },
3656 { O_EXEC, KF_FLAG_EXEC },
3657 { O_EXLOCK, KF_FLAG_EXLOCK },
3658 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3659 { O_SHLOCK, KF_FLAG_SHLOCK },
3660 { O_TRUNC, KF_FLAG_TRUNC }
3666 for (i = 0; i < nitems(fflags_table); i++)
3667 if (fflags & fflags_table[i].fflag)
3668 kflags |= fflags_table[i].kf_fflag;
3672 /* Trim unused data from kf_path by truncating the structure size. */
3674 pack_kinfo(struct kinfo_file *kif)
3677 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3678 strlen(kif->kf_path) + 1;
3679 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3683 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3684 struct kinfo_file *kif, struct filedesc *fdp, int flags)
3688 bzero(kif, sizeof(*kif));
3690 /* Set a default type to allow for empty fill_kinfo() methods. */
3691 kif->kf_type = KF_TYPE_UNKNOWN;
3692 kif->kf_flags = xlate_fflags(fp->f_flag);
3693 if (rightsp != NULL)
3694 kif->kf_cap_rights = *rightsp;
3696 cap_rights_init_zero(&kif->kf_cap_rights);
3698 kif->kf_ref_count = fp->f_count;
3699 kif->kf_offset = foffset_get(fp);
3702 * This may drop the filedesc lock, so the 'fp' cannot be
3703 * accessed after this call.
3705 error = fo_fill_kinfo(fp, kif, fdp);
3707 kif->kf_status |= KF_ATTR_VALID;
3708 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3711 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3715 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3716 struct kinfo_file *kif, int flags)
3720 bzero(kif, sizeof(*kif));
3722 kif->kf_type = KF_TYPE_VNODE;
3723 error = vn_fill_kinfo_vnode(vp, kif);
3725 kif->kf_status |= KF_ATTR_VALID;
3726 kif->kf_flags = xlate_fflags(fflags);
3727 cap_rights_init_zero(&kif->kf_cap_rights);
3729 kif->kf_ref_count = -1;
3730 kif->kf_offset = -1;
3731 if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
3734 kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
3738 struct export_fd_buf {
3739 struct filedesc *fdp;
3742 struct kinfo_file kif;
3747 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3749 struct kinfo_file *kif;
3752 if (efbuf->remainder != -1) {
3753 if (efbuf->remainder < kif->kf_structsize) {
3754 /* Terminate export. */
3755 efbuf->remainder = 0;
3758 efbuf->remainder -= kif->kf_structsize;
3760 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3764 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3765 struct export_fd_buf *efbuf)
3769 if (efbuf->remainder == 0)
3771 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
3773 FILEDESC_SUNLOCK(efbuf->fdp);
3774 error = export_kinfo_to_sb(efbuf);
3775 FILEDESC_SLOCK(efbuf->fdp);
3780 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3781 struct export_fd_buf *efbuf)
3785 if (efbuf->remainder == 0)
3787 if (efbuf->fdp != NULL)
3788 FILEDESC_SUNLOCK(efbuf->fdp);
3789 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
3790 error = export_kinfo_to_sb(efbuf);
3791 if (efbuf->fdp != NULL)
3792 FILEDESC_SLOCK(efbuf->fdp);
3797 * Store a process file descriptor information to sbuf.
3799 * Takes a locked proc as argument, and returns with the proc unlocked.
3802 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen,
3806 struct filedesc *fdp;
3807 struct export_fd_buf *efbuf;
3808 struct vnode *cttyvp, *textvp, *tracevp;
3811 cap_rights_t rights;
3813 PROC_LOCK_ASSERT(p, MA_OWNED);
3816 tracevp = p->p_tracevp;
3817 if (tracevp != NULL)
3820 textvp = p->p_textvp;
3823 /* Controlling tty. */
3825 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3826 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3832 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3835 efbuf->remainder = maxlen;
3836 efbuf->flags = flags;
3837 if (tracevp != NULL)
3838 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3841 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3843 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3849 FILEDESC_SLOCK(fdp);
3850 pwd = pwd_hold_filedesc(fdp);
3852 /* working directory */
3853 if (pwd->pwd_cdir != NULL) {
3854 vrefact(pwd->pwd_cdir);
3855 export_vnode_to_sb(pwd->pwd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3857 /* root directory */
3858 if (pwd->pwd_rdir != NULL) {
3859 vrefact(pwd->pwd_rdir);
3860 export_vnode_to_sb(pwd->pwd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3862 /* jail directory */
3863 if (pwd->pwd_jdir != NULL) {
3864 vrefact(pwd->pwd_jdir);
3865 export_vnode_to_sb(pwd->pwd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3869 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3870 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3873 rights = *cap_rights(fdp, i);
3874 #else /* !CAPABILITIES */
3875 rights = cap_no_rights;
3878 * Create sysctl entry. It is OK to drop the filedesc
3879 * lock inside of export_file_to_sb() as we will
3880 * re-validate and re-evaluate its properties when the
3883 error = export_file_to_sb(fp, i, &rights, efbuf);
3884 if (error != 0 || efbuf->remainder == 0)
3887 FILEDESC_SUNLOCK(fdp);
3890 free(efbuf, M_TEMP);
3894 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3897 * Get per-process file descriptors for use by procstat(1), et al.
3900 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3905 int error, error2, *name;
3909 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3910 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3911 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3916 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3917 error = kern_proc_filedesc_out(p, &sb, maxlen,
3918 KERN_FILEDESC_PACK_KINFO);
3919 error2 = sbuf_finish(&sb);
3921 return (error != 0 ? error : error2);
3924 #ifdef COMPAT_FREEBSD7
3925 #ifdef KINFO_OFILE_SIZE
3926 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3930 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3933 okif->kf_structsize = sizeof(*okif);
3934 okif->kf_type = kif->kf_type;
3935 okif->kf_fd = kif->kf_fd;
3936 okif->kf_ref_count = kif->kf_ref_count;
3937 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3938 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3939 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3940 okif->kf_offset = kif->kf_offset;
3941 if (kif->kf_type == KF_TYPE_VNODE)
3942 okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
3944 okif->kf_vnode_type = KF_VTYPE_VNON;
3945 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3946 if (kif->kf_type == KF_TYPE_SOCKET) {
3947 okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
3948 okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
3949 okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
3950 okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
3951 okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
3953 okif->kf_sa_local.ss_family = AF_UNSPEC;
3954 okif->kf_sa_peer.ss_family = AF_UNSPEC;
3959 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3960 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3965 FILEDESC_SUNLOCK(fdp);
3966 export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
3967 kinfo_to_okinfo(kif, okif);
3968 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3969 FILEDESC_SLOCK(fdp);
3974 * Get per-process file descriptors for use by procstat(1), et al.
3977 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3979 struct kinfo_ofile *okif;
3980 struct kinfo_file *kif;
3981 struct filedesc *fdp;
3983 int error, i, *name;
3988 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3995 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3996 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3997 FILEDESC_SLOCK(fdp);
3998 pwd = pwd_hold_filedesc(fdp);
4000 if (pwd->pwd_cdir != NULL)
4001 export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4003 if (pwd->pwd_rdir != NULL)
4004 export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4006 if (pwd->pwd_jdir != NULL)
4007 export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4011 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
4012 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
4014 export_file_to_kinfo(fp, i, NULL, kif, fdp,
4015 KERN_FILEDESC_PACK_KINFO);
4016 FILEDESC_SUNLOCK(fdp);
4017 kinfo_to_okinfo(kif, okif);
4018 error = SYSCTL_OUT(req, okif, sizeof(*okif));
4019 FILEDESC_SLOCK(fdp);
4023 FILEDESC_SUNLOCK(fdp);
4030 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4031 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4032 "Process ofiledesc entries");
4033 #endif /* COMPAT_FREEBSD7 */
4036 vntype_to_kinfo(int vtype)
4041 } vtypes_table[] = {
4042 { VBAD, KF_VTYPE_VBAD },
4043 { VBLK, KF_VTYPE_VBLK },
4044 { VCHR, KF_VTYPE_VCHR },
4045 { VDIR, KF_VTYPE_VDIR },
4046 { VFIFO, KF_VTYPE_VFIFO },
4047 { VLNK, KF_VTYPE_VLNK },
4048 { VNON, KF_VTYPE_VNON },
4049 { VREG, KF_VTYPE_VREG },
4050 { VSOCK, KF_VTYPE_VSOCK }
4055 * Perform vtype translation.
4057 for (i = 0; i < nitems(vtypes_table); i++)
4058 if (vtypes_table[i].vtype == vtype)
4059 return (vtypes_table[i].kf_vtype);
4061 return (KF_VTYPE_UNKNOWN);
4064 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4065 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4066 "Process filedesc entries");
4069 * Store a process current working directory information to sbuf.
4071 * Takes a locked proc as argument, and returns with the proc unlocked.
4074 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
4076 struct filedesc *fdp;
4077 struct export_fd_buf *efbuf;
4081 PROC_LOCK_ASSERT(p, MA_OWNED);
4088 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4091 efbuf->remainder = maxlen;
4093 FILEDESC_SLOCK(fdp);
4094 cdir = fdp->fd_pwd->pwd_cdir;
4099 error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4101 FILEDESC_SUNLOCK(fdp);
4103 free(efbuf, M_TEMP);
4108 * Get per-process current working directory.
4111 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4116 int error, error2, *name;
4120 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
4121 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4122 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4127 maxlen = req->oldptr != NULL ? req->oldlen : -1;
4128 error = kern_proc_cwd_out(p, &sb, maxlen);
4129 error2 = sbuf_finish(&sb);
4131 return (error != 0 ? error : error2);
4134 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
4135 sysctl_kern_proc_cwd, "Process current working directory");
4139 * For the purposes of debugging, generate a human-readable string for the
4143 file_type_to_name(short type)
4171 case DTYPE_PROCDESC:
4173 case DTYPE_LINUXEFD:
4175 case DTYPE_LINUXTFD:
4183 * For the purposes of debugging, identify a process (if any, perhaps one of
4184 * many) that references the passed file in its file descriptor array. Return
4187 static struct proc *
4188 file_to_first_proc(struct file *fp)
4190 struct filedesc *fdp;
4194 FOREACH_PROC_IN_SYSTEM(p) {
4195 if (p->p_state == PRS_NEW)
4200 for (n = 0; n <= fdp->fd_lastfile; n++) {
4201 if (fp == fdp->fd_ofiles[n].fde_file)
4209 db_print_file(struct file *fp, int header)
4211 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
4215 db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
4216 XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
4217 "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
4219 p = file_to_first_proc(fp);
4220 db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
4221 fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
4222 fp->f_flag, 0, fp->f_count, 0, XPTRWIDTH, fp->f_vnode,
4223 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
4228 DB_SHOW_COMMAND(file, db_show_file)
4233 db_printf("usage: show file <addr>\n");
4236 fp = (struct file *)addr;
4237 db_print_file(fp, 1);
4240 DB_SHOW_COMMAND(files, db_show_files)
4242 struct filedesc *fdp;
4249 FOREACH_PROC_IN_SYSTEM(p) {
4250 if (p->p_state == PRS_NEW)
4252 if ((fdp = p->p_fd) == NULL)
4254 for (n = 0; n <= fdp->fd_lastfile; ++n) {
4255 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
4257 db_print_file(fp, header);
4264 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
4265 &maxfilesperproc, 0, "Maximum files allowed open per process");
4267 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
4268 &maxfiles, 0, "Maximum number of files");
4270 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
4271 &openfiles, 0, "System-wide number of open files");
4275 filelistinit(void *dummy)
4278 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
4279 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
4280 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
4281 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
4282 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
4284 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
4286 /*-------------------------------------------------------------------*/
4289 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
4290 int flags, struct thread *td)
4297 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4305 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
4313 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
4321 badfo_kqfilter(struct file *fp, struct knote *kn)
4328 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
4336 badfo_close(struct file *fp, struct thread *td)
4343 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4351 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4359 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4360 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4368 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
4374 struct fileops badfileops = {
4375 .fo_read = badfo_readwrite,
4376 .fo_write = badfo_readwrite,
4377 .fo_truncate = badfo_truncate,
4378 .fo_ioctl = badfo_ioctl,
4379 .fo_poll = badfo_poll,
4380 .fo_kqfilter = badfo_kqfilter,
4381 .fo_stat = badfo_stat,
4382 .fo_close = badfo_close,
4383 .fo_chmod = badfo_chmod,
4384 .fo_chown = badfo_chown,
4385 .fo_sendfile = badfo_sendfile,
4386 .fo_fill_kinfo = badfo_fill_kinfo,
4390 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
4391 int flags, struct thread *td)
4394 return (EOPNOTSUPP);
4398 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
4406 invfo_ioctl(struct file *fp, u_long com, void *data,
4407 struct ucred *active_cred, struct thread *td)
4414 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
4418 return (poll_no_poll(events));
4422 invfo_kqfilter(struct file *fp, struct knote *kn)
4429 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4437 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4445 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
4446 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
4453 /*-------------------------------------------------------------------*/
4456 * File Descriptor pseudo-device driver (/dev/fd/).
4458 * Opening minor device N dup()s the file (if any) connected to file
4459 * descriptor N belonging to the calling process. Note that this driver
4460 * consists of only the ``open()'' routine, because all subsequent
4461 * references to this file will be direct to the other driver.
4463 * XXX: we could give this one a cloning event handler if necessary.
4468 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4472 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4473 * the file descriptor being sought for duplication. The error
4474 * return ensures that the vnode for this device will be released
4475 * by vn_open. Open will detect this special error and take the
4476 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4477 * will simply report the error.
4479 td->td_dupfd = dev2unit(dev);
4483 static struct cdevsw fildesc_cdevsw = {
4484 .d_version = D_VERSION,
4490 fildesc_drvinit(void *unused)
4494 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4495 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4496 make_dev_alias(dev, "stdin");
4497 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4498 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4499 make_dev_alias(dev, "stdout");
4500 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4501 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4502 make_dev_alias(dev, "stderr");
4505 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);