2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_compat.h"
42 #include "opt_ktrace.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
48 #include <sys/domain.h>
49 #include <sys/fcntl.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
54 #include <sys/kernel.h>
55 #include <sys/limits.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/mqueue.h>
60 #include <sys/mutex.h>
61 #include <sys/namei.h>
64 #include <sys/protosw.h>
65 #include <sys/resourcevar.h>
66 #include <sys/signalvar.h>
67 #include <sys/socketvar.h>
70 #include <sys/syscallsubr.h>
71 #include <sys/sysctl.h>
72 #include <sys/sysproto.h>
73 #include <sys/unistd.h>
75 #include <sys/vnode.h>
77 #include <sys/ktrace.h>
80 #include <security/audit/audit.h>
86 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
87 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
88 "file desc to leader structures");
89 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
91 static uma_zone_t file_zone;
94 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
95 enum dup_type { DUP_VARIABLE, DUP_FIXED };
97 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
99 static int fd_first_free(struct filedesc *, int, int);
100 static int fd_last_used(struct filedesc *, int, int);
101 static void fdgrowtable(struct filedesc *, int);
102 static int fdrop_locked(struct file *fp, struct thread *td);
103 static void fdunused(struct filedesc *fdp, int fd);
104 static void fdused(struct filedesc *fdp, int fd);
107 * A process is initially started out with NDFILE descriptors stored within
108 * this structure, selected to be enough for typical applications based on
109 * the historical limit of 20 open files (and the usage of descriptors by
110 * shells). If these descriptors are exhausted, a larger descriptor table
111 * may be allocated, up to a process' resource limit; the internal arrays
115 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
116 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
117 #define NDSLOT(x) ((x) / NDENTRIES)
118 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
119 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
122 * Storage required per open file descriptor.
124 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
127 * Basic allocation of descriptors:
128 * one of the above, plus arrays for NDFILE descriptors.
131 struct filedesc fd_fd;
133 * These arrays are used when the number of open files is
134 * <= NDFILE, and are then pointed to by the pointers above.
136 struct file *fd_dfiles[NDFILE];
137 char fd_dfileflags[NDFILE];
138 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
142 * Descriptor management.
144 struct filelist filehead; /* head of list of open files */
145 int openfiles; /* actual number of open files */
146 struct sx filelist_lock; /* sx to protect filelist */
147 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
148 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
150 /* A mutex to protect the association between a proc and filedesc. */
151 static struct mtx fdesc_mtx;
154 * Find the first zero bit in the given bitmap, starting at low and not
155 * exceeding size - 1.
158 fd_first_free(struct filedesc *fdp, int low, int size)
160 NDSLOTTYPE *map = fdp->fd_map;
168 if (low % NDENTRIES) {
169 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
170 if ((mask &= ~map[off]) != 0UL)
171 return (off * NDENTRIES + ffsl(mask) - 1);
174 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
175 if (map[off] != ~0UL)
176 return (off * NDENTRIES + ffsl(~map[off]) - 1);
181 * Find the highest non-zero bit in the given bitmap, starting at low and
182 * not exceeding size - 1.
185 fd_last_used(struct filedesc *fdp, int low, int size)
187 NDSLOTTYPE *map = fdp->fd_map;
195 if (size % NDENTRIES) {
196 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
197 if ((mask &= map[off]) != 0)
198 return (off * NDENTRIES + flsl(mask) - 1);
201 for (minoff = NDSLOT(low); off >= minoff; --off)
203 return (off * NDENTRIES + flsl(map[off]) - 1);
208 fdisused(struct filedesc *fdp, int fd)
210 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
211 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
212 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
216 * Mark a file descriptor as used.
219 fdused(struct filedesc *fdp, int fd)
222 FILEDESC_XLOCK_ASSERT(fdp);
223 KASSERT(!fdisused(fdp, fd),
224 ("fd already used"));
226 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
227 if (fd > fdp->fd_lastfile)
228 fdp->fd_lastfile = fd;
229 if (fd == fdp->fd_freefile)
230 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
234 * Mark a file descriptor as unused.
237 fdunused(struct filedesc *fdp, int fd)
240 FILEDESC_XLOCK_ASSERT(fdp);
241 KASSERT(fdisused(fdp, fd),
242 ("fd is already unused"));
243 KASSERT(fdp->fd_ofiles[fd] == NULL,
244 ("fd is still in use"));
246 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
247 if (fd < fdp->fd_freefile)
248 fdp->fd_freefile = fd;
249 if (fd == fdp->fd_lastfile)
250 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
254 * System calls on descriptors.
256 #ifndef _SYS_SYSPROTO_H_
257 struct getdtablesize_args {
263 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
265 struct proc *p = td->td_proc;
269 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
275 * Duplicate a file descriptor to a particular value.
277 * Note: keep in mind that a potential race condition exists when closing
278 * descriptors from a shared descriptor table (via rfork).
280 #ifndef _SYS_SYSPROTO_H_
288 dup2(struct thread *td, struct dup2_args *uap)
291 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
296 * Duplicate a file descriptor.
298 #ifndef _SYS_SYSPROTO_H_
305 dup(struct thread *td, struct dup_args *uap)
308 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
312 * The file control system call.
314 #ifndef _SYS_SYSPROTO_H_
323 fcntl(struct thread *td, struct fcntl_args *uap)
338 * Convert old flock structure to new.
340 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
341 fl.l_start = ofl.l_start;
342 fl.l_len = ofl.l_len;
343 fl.l_pid = ofl.l_pid;
344 fl.l_type = ofl.l_type;
345 fl.l_whence = ofl.l_whence;
365 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
374 error = kern_fcntl(td, uap->fd, cmd, arg);
377 if (uap->cmd == F_OGETLK) {
378 ofl.l_start = fl.l_start;
379 ofl.l_len = fl.l_len;
380 ofl.l_pid = fl.l_pid;
381 ofl.l_type = fl.l_type;
382 ofl.l_whence = fl.l_whence;
383 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
384 } else if (uap->cmd == F_GETLK) {
385 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
390 static inline struct file *
391 fdtofp(int fd, struct filedesc *fdp)
395 FILEDESC_LOCK_ASSERT(fdp);
396 if ((unsigned)fd >= fdp->fd_nfiles ||
397 (fp = fdp->fd_ofiles[fd]) == NULL)
403 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
405 struct filedesc *fdp;
424 if ((fp = fdtofp(fd, fdp)) == NULL) {
425 FILEDESC_SUNLOCK(fdp);
429 FILEDESC_SUNLOCK(fdp);
432 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
433 newmin >= maxfilesperproc) {
439 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
444 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
449 if ((fp = fdtofp(fd, fdp)) == NULL) {
450 FILEDESC_SUNLOCK(fdp);
454 pop = &fdp->fd_ofileflags[fd];
455 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
456 FILEDESC_SUNLOCK(fdp);
461 if ((fp = fdtofp(fd, fdp)) == NULL) {
462 FILEDESC_XUNLOCK(fdp);
466 pop = &fdp->fd_ofileflags[fd];
467 *pop = (*pop &~ UF_EXCLOSE) |
468 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
469 FILEDESC_XUNLOCK(fdp);
474 if ((fp = fdtofp(fd, fdp)) == NULL) {
475 FILEDESC_SUNLOCK(fdp);
480 td->td_retval[0] = OFLAGS(fp->f_flag);
482 FILEDESC_SUNLOCK(fdp);
487 if ((fp = fdtofp(fd, fdp)) == NULL) {
488 FILEDESC_SUNLOCK(fdp);
494 fp->f_flag &= ~FCNTLFLAGS;
495 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
497 FILEDESC_SUNLOCK(fdp);
498 tmp = fp->f_flag & FNONBLOCK;
499 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
504 tmp = fp->f_flag & FASYNC;
505 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
511 fp->f_flag &= ~FNONBLOCK;
514 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
520 if ((fp = fdtofp(fd, fdp)) == NULL) {
521 FILEDESC_SUNLOCK(fdp);
526 FILEDESC_SUNLOCK(fdp);
527 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
529 td->td_retval[0] = tmp;
535 if ((fp = fdtofp(fd, fdp)) == NULL) {
536 FILEDESC_SUNLOCK(fdp);
541 FILEDESC_SUNLOCK(fdp);
543 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
548 error = priv_check(td, PRIV_NFS_LOCKD);
556 /* FALLTHROUGH F_SETLK */
561 if ((fp = fdtofp(fd, fdp)) == NULL) {
562 FILEDESC_SUNLOCK(fdp);
566 if (fp->f_type != DTYPE_VNODE) {
567 FILEDESC_SUNLOCK(fdp);
571 flp = (struct flock *)arg;
572 if (flp->l_whence == SEEK_CUR) {
573 if (fp->f_offset < 0 ||
575 fp->f_offset > OFF_MAX - flp->l_start)) {
576 FILEDESC_SUNLOCK(fdp);
580 flp->l_start += fp->f_offset;
584 * VOP_ADVLOCK() may block.
587 FILEDESC_SUNLOCK(fdp);
589 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
590 switch (flp->l_type) {
592 if ((fp->f_flag & FREAD) == 0) {
596 PROC_LOCK(p->p_leader);
597 p->p_leader->p_flag |= P_ADVLOCK;
598 PROC_UNLOCK(p->p_leader);
599 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
603 if ((fp->f_flag & FWRITE) == 0) {
607 PROC_LOCK(p->p_leader);
608 p->p_leader->p_flag |= P_ADVLOCK;
609 PROC_UNLOCK(p->p_leader);
610 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
614 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
619 * Temporary api for testing remote lock
622 if (flg != F_REMOTE) {
626 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
627 F_UNLCKSYS, flp, flg);
633 VFS_UNLOCK_GIANT(vfslocked);
635 /* Check for race with close */
637 if ((unsigned) fd >= fdp->fd_nfiles ||
638 fp != fdp->fd_ofiles[fd]) {
639 FILEDESC_SUNLOCK(fdp);
640 flp->l_whence = SEEK_SET;
643 flp->l_type = F_UNLCK;
644 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
645 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
646 F_UNLCK, flp, F_POSIX);
647 VFS_UNLOCK_GIANT(vfslocked);
650 FILEDESC_SUNLOCK(fdp);
656 if ((fp = fdtofp(fd, fdp)) == NULL) {
657 FILEDESC_SUNLOCK(fdp);
661 if (fp->f_type != DTYPE_VNODE) {
662 FILEDESC_SUNLOCK(fdp);
666 flp = (struct flock *)arg;
667 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
668 flp->l_type != F_UNLCK) {
669 FILEDESC_SUNLOCK(fdp);
673 if (flp->l_whence == SEEK_CUR) {
674 if ((flp->l_start > 0 &&
675 fp->f_offset > OFF_MAX - flp->l_start) ||
677 fp->f_offset < OFF_MIN - flp->l_start)) {
678 FILEDESC_SUNLOCK(fdp);
682 flp->l_start += fp->f_offset;
685 * VOP_ADVLOCK() may block.
688 FILEDESC_SUNLOCK(fdp);
690 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
691 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
693 VFS_UNLOCK_GIANT(vfslocked);
701 VFS_UNLOCK_GIANT(vfslocked);
706 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
709 do_dup(struct thread *td, enum dup_type type, int old, int new,
712 struct filedesc *fdp;
716 int error, holdleaders, maxfd;
718 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
719 ("invalid dup type %d", type));
725 * Verify we have a valid descriptor to dup from and possibly to
728 if (old < 0 || new < 0)
731 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
737 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
738 FILEDESC_XUNLOCK(fdp);
741 if (type == DUP_FIXED && old == new) {
743 FILEDESC_XUNLOCK(fdp);
746 fp = fdp->fd_ofiles[old];
750 * If the caller specified a file descriptor, make sure the file
751 * table is large enough to hold it, and grab it. Otherwise, just
752 * allocate a new descriptor the usual way. Since the filedesc
753 * lock may be temporarily dropped in the process, we have to look
756 if (type == DUP_FIXED) {
757 if (new >= fdp->fd_nfiles)
758 fdgrowtable(fdp, new + 1);
759 if (fdp->fd_ofiles[new] == NULL)
762 if ((error = fdalloc(td, new, &new)) != 0) {
763 FILEDESC_XUNLOCK(fdp);
770 * If the old file changed out from under us then treat it as a
771 * bad file descriptor. Userland should do its own locking to
774 if (fdp->fd_ofiles[old] != fp) {
775 /* we've allocated a descriptor which we won't use */
776 if (fdp->fd_ofiles[new] == NULL)
778 FILEDESC_XUNLOCK(fdp);
783 ("new fd is same as old"));
786 * Save info on the descriptor being overwritten. We cannot close
787 * it without introducing an ownership race for the slot, since we
788 * need to drop the filedesc lock to call closef().
790 * XXX this duplicates parts of close().
792 delfp = fdp->fd_ofiles[new];
795 if (td->td_proc->p_fdtol != NULL) {
797 * Ask fdfree() to sleep to ensure that all relevant
798 * process leaders can be traversed in closef().
800 fdp->fd_holdleaderscount++;
806 * Duplicate the source descriptor
808 fdp->fd_ofiles[new] = fp;
809 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
810 if (new > fdp->fd_lastfile)
811 fdp->fd_lastfile = new;
815 * If we dup'd over a valid file, we now own the reference to it
816 * and must dispose of it using closef() semantics (as if a
817 * close() were performed on it).
819 * XXX this duplicates parts of close().
822 knote_fdclose(td, new);
823 if (delfp->f_type == DTYPE_MQUEUE)
824 mq_fdclose(td, new, delfp);
825 FILEDESC_XUNLOCK(fdp);
826 (void) closef(delfp, td);
829 fdp->fd_holdleaderscount--;
830 if (fdp->fd_holdleaderscount == 0 &&
831 fdp->fd_holdleaderswakeup != 0) {
832 fdp->fd_holdleaderswakeup = 0;
833 wakeup(&fdp->fd_holdleaderscount);
835 FILEDESC_XUNLOCK(fdp);
838 FILEDESC_XUNLOCK(fdp);
844 * If sigio is on the list associated with a process or process group,
845 * disable signalling from the device, remove sigio from the list and
849 funsetown(struct sigio **sigiop)
859 *(sigio->sio_myref) = NULL;
860 if ((sigio)->sio_pgid < 0) {
861 struct pgrp *pg = (sigio)->sio_pgrp;
863 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
867 struct proc *p = (sigio)->sio_proc;
869 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
874 crfree(sigio->sio_ucred);
875 FREE(sigio, M_SIGIO);
879 * Free a list of sigio structures.
880 * We only need to lock the SIGIO_LOCK because we have made ourselves
881 * inaccessible to callers of fsetown and therefore do not need to lock
882 * the proc or pgrp struct for the list manipulation.
885 funsetownlst(struct sigiolst *sigiolst)
891 sigio = SLIST_FIRST(sigiolst);
898 * Every entry of the list should belong
899 * to a single proc or pgrp.
901 if (sigio->sio_pgid < 0) {
902 pg = sigio->sio_pgrp;
903 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
904 } else /* if (sigio->sio_pgid > 0) */ {
906 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
910 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
911 *(sigio->sio_myref) = NULL;
913 KASSERT(sigio->sio_pgid < 0,
914 ("Proc sigio in pgrp sigio list"));
915 KASSERT(sigio->sio_pgrp == pg,
916 ("Bogus pgrp in sigio list"));
918 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
921 } else /* if (p != NULL) */ {
922 KASSERT(sigio->sio_pgid > 0,
923 ("Pgrp sigio in proc sigio list"));
924 KASSERT(sigio->sio_proc == p,
925 ("Bogus proc in sigio list"));
927 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
932 crfree(sigio->sio_ucred);
933 FREE(sigio, M_SIGIO);
940 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
942 * After permission checking, add a sigio structure to the sigio list for
943 * the process or process group.
946 fsetown(pid_t pgid, struct sigio **sigiop)
960 /* Allocate and fill in the new sigio out of locks. */
961 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
962 sigio->sio_pgid = pgid;
963 sigio->sio_ucred = crhold(curthread->td_ucred);
964 sigio->sio_myref = sigiop;
966 sx_slock(&proctree_lock);
975 * Policy - Don't allow a process to FSETOWN a process
976 * in another session.
978 * Remove this test to allow maximum flexibility or
979 * restrict FSETOWN to the current process or process
980 * group for maximum safety.
983 if (proc->p_session != curthread->td_proc->p_session) {
989 } else /* if (pgid < 0) */ {
990 pgrp = pgfind(-pgid);
998 * Policy - Don't allow a process to FSETOWN a process
999 * in another session.
1001 * Remove this test to allow maximum flexibility or
1002 * restrict FSETOWN to the current process or process
1003 * group for maximum safety.
1005 if (pgrp->pg_session != curthread->td_proc->p_session) {
1016 * Since funsetownlst() is called without the proctree
1017 * locked, we need to check for P_WEXIT.
1018 * XXX: is ESRCH correct?
1020 if ((proc->p_flag & P_WEXIT) != 0) {
1025 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1026 sigio->sio_proc = proc;
1030 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1031 sigio->sio_pgrp = pgrp;
1034 sx_sunlock(&proctree_lock);
1041 sx_sunlock(&proctree_lock);
1042 crfree(sigio->sio_ucred);
1043 FREE(sigio, M_SIGIO);
1048 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1052 struct sigio **sigiop;
1057 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1063 * Close a file descriptor.
1065 #ifndef _SYS_SYSPROTO_H_
1074 struct close_args *uap;
1077 return (kern_close(td, uap->fd));
1085 struct filedesc *fdp;
1092 fdp = td->td_proc->p_fd;
1094 AUDIT_SYSCLOSE(td, fd);
1096 FILEDESC_XLOCK(fdp);
1097 if ((unsigned)fd >= fdp->fd_nfiles ||
1098 (fp = fdp->fd_ofiles[fd]) == NULL) {
1099 FILEDESC_XUNLOCK(fdp);
1102 fdp->fd_ofiles[fd] = NULL;
1103 fdp->fd_ofileflags[fd] = 0;
1105 if (td->td_proc->p_fdtol != NULL) {
1107 * Ask fdfree() to sleep to ensure that all relevant
1108 * process leaders can be traversed in closef().
1110 fdp->fd_holdleaderscount++;
1115 * We now hold the fp reference that used to be owned by the
1116 * descriptor array. We have to unlock the FILEDESC *AFTER*
1117 * knote_fdclose to prevent a race of the fd getting opened, a knote
1118 * added, and deleteing a knote for the new fd.
1120 knote_fdclose(td, fd);
1121 if (fp->f_type == DTYPE_MQUEUE)
1122 mq_fdclose(td, fd, fp);
1123 FILEDESC_XUNLOCK(fdp);
1125 error = closef(fp, td);
1127 FILEDESC_XLOCK(fdp);
1128 fdp->fd_holdleaderscount--;
1129 if (fdp->fd_holdleaderscount == 0 &&
1130 fdp->fd_holdleaderswakeup != 0) {
1131 fdp->fd_holdleaderswakeup = 0;
1132 wakeup(&fdp->fd_holdleaderscount);
1134 FILEDESC_XUNLOCK(fdp);
1139 #if defined(COMPAT_43)
1141 * Return status information about a file descriptor.
1143 #ifndef _SYS_SYSPROTO_H_
1144 struct ofstat_args {
1151 ofstat(struct thread *td, struct ofstat_args *uap)
1157 error = kern_fstat(td, uap->fd, &ub);
1160 error = copyout(&oub, uap->sb, sizeof(oub));
1164 #endif /* COMPAT_43 */
1167 * Return status information about a file descriptor.
1169 #ifndef _SYS_SYSPROTO_H_
1177 fstat(struct thread *td, struct fstat_args *uap)
1182 error = kern_fstat(td, uap->fd, &ub);
1184 error = copyout(&ub, uap->sb, sizeof(ub));
1189 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1196 if ((error = fget(td, fd, &fp)) != 0)
1199 AUDIT_ARG(file, td->td_proc, fp);
1201 error = fo_stat(fp, sbp, td->td_ucred, td);
1204 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1211 * Return status information about a file descriptor.
1213 #ifndef _SYS_SYSPROTO_H_
1214 struct nfstat_args {
1221 nfstat(struct thread *td, struct nfstat_args *uap)
1227 error = kern_fstat(td, uap->fd, &ub);
1229 cvtnstat(&ub, &nub);
1230 error = copyout(&nub, uap->sb, sizeof(nub));
1236 * Return pathconf information about a file descriptor.
1238 #ifndef _SYS_SYSPROTO_H_
1239 struct fpathconf_args {
1246 fpathconf(struct thread *td, struct fpathconf_args *uap)
1252 if ((error = fget(td, uap->fd, &fp)) != 0)
1255 /* If asynchronous I/O is available, it works for all descriptors. */
1256 if (uap->name == _PC_ASYNC_IO) {
1257 td->td_retval[0] = async_io_version;
1263 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1264 vn_lock(vp, LK_SHARED | LK_RETRY, td);
1265 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1266 VOP_UNLOCK(vp, 0, td);
1267 VFS_UNLOCK_GIANT(vfslocked);
1268 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1269 if (uap->name != _PC_PIPE_BUF) {
1272 td->td_retval[0] = PIPE_BUF;
1284 * Grow the file table to accomodate (at least) nfd descriptors. This may
1285 * block and drop the filedesc lock, but it will reacquire it before
1289 fdgrowtable(struct filedesc *fdp, int nfd)
1291 struct file **ntable;
1293 int nnfiles, onfiles;
1296 FILEDESC_XLOCK_ASSERT(fdp);
1298 KASSERT(fdp->fd_nfiles > 0,
1299 ("zero-length file table"));
1301 /* compute the size of the new table */
1302 onfiles = fdp->fd_nfiles;
1303 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1304 if (nnfiles <= onfiles)
1305 /* the table is already large enough */
1308 /* allocate a new table and (if required) new bitmaps */
1309 FILEDESC_XUNLOCK(fdp);
1310 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1311 M_FILEDESC, M_ZERO | M_WAITOK);
1312 nfileflags = (char *)&ntable[nnfiles];
1313 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1314 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1315 M_FILEDESC, M_ZERO | M_WAITOK);
1318 FILEDESC_XLOCK(fdp);
1321 * We now have new tables ready to go. Since we dropped the
1322 * filedesc lock to call malloc(), watch out for a race.
1324 onfiles = fdp->fd_nfiles;
1325 if (onfiles >= nnfiles) {
1326 /* we lost the race, but that's OK */
1327 free(ntable, M_FILEDESC);
1329 free(nmap, M_FILEDESC);
1332 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1333 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1334 if (onfiles > NDFILE)
1335 free(fdp->fd_ofiles, M_FILEDESC);
1336 fdp->fd_ofiles = ntable;
1337 fdp->fd_ofileflags = nfileflags;
1338 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1339 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1340 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1341 free(fdp->fd_map, M_FILEDESC);
1344 fdp->fd_nfiles = nnfiles;
1348 * Allocate a file descriptor for the process.
1351 fdalloc(struct thread *td, int minfd, int *result)
1353 struct proc *p = td->td_proc;
1354 struct filedesc *fdp = p->p_fd;
1357 FILEDESC_XLOCK_ASSERT(fdp);
1359 if (fdp->fd_freefile > minfd)
1360 minfd = fdp->fd_freefile;
1363 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1367 * Search the bitmap for a free descriptor. If none is found, try
1368 * to grow the file table. Keep at it until we either get a file
1369 * descriptor or run into process or system limits; fdgrowtable()
1370 * may drop the filedesc lock, so we're in a race.
1373 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1376 if (fd < fdp->fd_nfiles)
1378 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1382 * Perform some sanity checks, then mark the file descriptor as
1383 * used and return it to the caller.
1385 KASSERT(!fdisused(fdp, fd),
1386 ("fd_first_free() returned non-free descriptor"));
1387 KASSERT(fdp->fd_ofiles[fd] == NULL,
1388 ("free descriptor isn't"));
1389 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1396 * Check to see whether n user file descriptors are available to the process
1400 fdavail(struct thread *td, int n)
1402 struct proc *p = td->td_proc;
1403 struct filedesc *fdp = td->td_proc->p_fd;
1407 FILEDESC_LOCK_ASSERT(fdp);
1410 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1412 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1414 last = min(fdp->fd_nfiles, lim);
1415 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1416 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1417 if (*fpp == NULL && --n <= 0)
1424 * Create a new open file structure and allocate a file decriptor for the
1425 * process that refers to it. We add one reference to the file for the
1426 * descriptor table and one reference for resultfp. This is to prevent us
1427 * being preempted and the entry in the descriptor table closed after we
1428 * release the FILEDESC lock.
1431 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1433 struct proc *p = td->td_proc;
1434 struct file *fp, *fq;
1436 int maxuserfiles = maxfiles - (maxfiles / 20);
1437 static struct timeval lastfail;
1440 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1441 sx_xlock(&filelist_lock);
1443 if ((openfiles >= maxuserfiles &&
1444 priv_check(td, PRIV_MAXFILES) != 0) ||
1445 openfiles >= maxfiles) {
1446 if (ppsratecheck(&lastfail, &curfail, 1)) {
1447 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1448 td->td_ucred->cr_ruid);
1450 sx_xunlock(&filelist_lock);
1451 uma_zfree(file_zone, fp);
1457 * If the process has file descriptor zero open, add the new file
1458 * descriptor to the list of open files at that point, otherwise
1459 * put it at the front of the list of open files.
1461 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1465 fp->f_cred = crhold(td->td_ucred);
1466 fp->f_ops = &badfileops;
1469 FILEDESC_XLOCK(p->p_fd);
1470 if ((fq = p->p_fd->fd_ofiles[0])) {
1471 LIST_INSERT_AFTER(fq, fp, f_list);
1473 LIST_INSERT_HEAD(&filehead, fp, f_list);
1475 sx_xunlock(&filelist_lock);
1476 if ((error = fdalloc(td, 0, &i))) {
1477 FILEDESC_XUNLOCK(p->p_fd);
1483 p->p_fd->fd_ofiles[i] = fp;
1484 FILEDESC_XUNLOCK(p->p_fd);
1493 * Build a new filedesc structure from another.
1494 * Copy the current, root, and jail root vnode references.
1497 fdinit(struct filedesc *fdp)
1499 struct filedesc0 *newfdp;
1501 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1502 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1504 FILEDESC_XLOCK(fdp);
1505 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1506 if (newfdp->fd_fd.fd_cdir)
1507 VREF(newfdp->fd_fd.fd_cdir);
1508 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1509 if (newfdp->fd_fd.fd_rdir)
1510 VREF(newfdp->fd_fd.fd_rdir);
1511 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1512 if (newfdp->fd_fd.fd_jdir)
1513 VREF(newfdp->fd_fd.fd_jdir);
1514 FILEDESC_XUNLOCK(fdp);
1517 /* Create the file descriptor table. */
1518 newfdp->fd_fd.fd_refcnt = 1;
1519 newfdp->fd_fd.fd_holdcnt = 1;
1520 newfdp->fd_fd.fd_cmask = CMASK;
1521 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1522 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1523 newfdp->fd_fd.fd_nfiles = NDFILE;
1524 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1525 newfdp->fd_fd.fd_lastfile = -1;
1526 return (&newfdp->fd_fd);
1529 static struct filedesc *
1530 fdhold(struct proc *p)
1532 struct filedesc *fdp;
1534 mtx_lock(&fdesc_mtx);
1538 mtx_unlock(&fdesc_mtx);
1543 fddrop(struct filedesc *fdp)
1547 mtx_lock(&fdesc_mtx);
1548 i = --fdp->fd_holdcnt;
1549 mtx_unlock(&fdesc_mtx);
1553 FILEDESC_LOCK_DESTROY(fdp);
1554 FREE(fdp, M_FILEDESC);
1558 * Share a filedesc structure.
1561 fdshare(struct filedesc *fdp)
1564 FILEDESC_XLOCK(fdp);
1566 FILEDESC_XUNLOCK(fdp);
1571 * Unshare a filedesc structure, if necessary by making a copy
1574 fdunshare(struct proc *p, struct thread *td)
1577 FILEDESC_XLOCK(p->p_fd);
1578 if (p->p_fd->fd_refcnt > 1) {
1579 struct filedesc *tmp;
1581 FILEDESC_XUNLOCK(p->p_fd);
1582 tmp = fdcopy(p->p_fd);
1586 FILEDESC_XUNLOCK(p->p_fd);
1590 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1591 * this is to ease callers, not catch errors.
1594 fdcopy(struct filedesc *fdp)
1596 struct filedesc *newfdp;
1599 /* Certain daemons might not have file descriptors. */
1603 newfdp = fdinit(fdp);
1604 FILEDESC_SLOCK(fdp);
1605 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1606 FILEDESC_SUNLOCK(fdp);
1607 FILEDESC_XLOCK(newfdp);
1608 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1609 FILEDESC_XUNLOCK(newfdp);
1610 FILEDESC_SLOCK(fdp);
1612 /* copy everything except kqueue descriptors */
1613 newfdp->fd_freefile = -1;
1614 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1615 if (fdisused(fdp, i) &&
1616 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1617 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1618 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1619 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1620 fhold(newfdp->fd_ofiles[i]);
1621 newfdp->fd_lastfile = i;
1623 if (newfdp->fd_freefile == -1)
1624 newfdp->fd_freefile = i;
1627 FILEDESC_SUNLOCK(fdp);
1628 FILEDESC_XLOCK(newfdp);
1629 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1630 if (newfdp->fd_ofiles[i] != NULL)
1632 FILEDESC_XUNLOCK(newfdp);
1633 FILEDESC_SLOCK(fdp);
1634 if (newfdp->fd_freefile == -1)
1635 newfdp->fd_freefile = i;
1636 newfdp->fd_cmask = fdp->fd_cmask;
1637 FILEDESC_SUNLOCK(fdp);
1642 * Release a filedesc structure.
1645 fdfree(struct thread *td)
1647 struct filedesc *fdp;
1650 struct filedesc_to_leader *fdtol;
1652 struct vnode *cdir, *jdir, *rdir, *vp;
1655 /* Certain daemons might not have file descriptors. */
1656 fdp = td->td_proc->p_fd;
1660 /* Check for special need to clear POSIX style locks */
1661 fdtol = td->td_proc->p_fdtol;
1662 if (fdtol != NULL) {
1663 FILEDESC_XLOCK(fdp);
1664 KASSERT(fdtol->fdl_refcount > 0,
1665 ("filedesc_to_refcount botch: fdl_refcount=%d",
1666 fdtol->fdl_refcount));
1667 if (fdtol->fdl_refcount == 1 &&
1668 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1669 for (i = 0, fpp = fdp->fd_ofiles;
1670 i <= fdp->fd_lastfile;
1673 (*fpp)->f_type != DTYPE_VNODE)
1677 FILEDESC_XUNLOCK(fdp);
1678 lf.l_whence = SEEK_SET;
1681 lf.l_type = F_UNLCK;
1683 locked = VFS_LOCK_GIANT(vp->v_mount);
1684 (void) VOP_ADVLOCK(vp,
1685 (caddr_t)td->td_proc->
1690 VFS_UNLOCK_GIANT(locked);
1691 FILEDESC_XLOCK(fdp);
1693 fpp = fdp->fd_ofiles + i;
1697 if (fdtol->fdl_refcount == 1) {
1698 if (fdp->fd_holdleaderscount > 0 &&
1699 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1701 * close() or do_dup() has cleared a reference
1702 * in a shared file descriptor table.
1704 fdp->fd_holdleaderswakeup = 1;
1705 sx_sleep(&fdp->fd_holdleaderscount,
1706 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1709 if (fdtol->fdl_holdcount > 0) {
1711 * Ensure that fdtol->fdl_leader remains
1712 * valid in closef().
1714 fdtol->fdl_wakeup = 1;
1715 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1720 fdtol->fdl_refcount--;
1721 if (fdtol->fdl_refcount == 0 &&
1722 fdtol->fdl_holdcount == 0) {
1723 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1724 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1727 td->td_proc->p_fdtol = NULL;
1728 FILEDESC_XUNLOCK(fdp);
1730 FREE(fdtol, M_FILEDESC_TO_LEADER);
1732 FILEDESC_XLOCK(fdp);
1733 i = --fdp->fd_refcnt;
1734 FILEDESC_XUNLOCK(fdp);
1738 fpp = fdp->fd_ofiles;
1739 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1741 FILEDESC_XLOCK(fdp);
1744 FILEDESC_XUNLOCK(fdp);
1745 (void) closef(fp, td);
1748 FILEDESC_XLOCK(fdp);
1750 /* XXX This should happen earlier. */
1751 mtx_lock(&fdesc_mtx);
1752 td->td_proc->p_fd = NULL;
1753 mtx_unlock(&fdesc_mtx);
1755 if (fdp->fd_nfiles > NDFILE)
1756 FREE(fdp->fd_ofiles, M_FILEDESC);
1757 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1758 FREE(fdp->fd_map, M_FILEDESC);
1762 cdir = fdp->fd_cdir;
1763 fdp->fd_cdir = NULL;
1764 rdir = fdp->fd_rdir;
1765 fdp->fd_rdir = NULL;
1766 jdir = fdp->fd_jdir;
1767 fdp->fd_jdir = NULL;
1768 FILEDESC_XUNLOCK(fdp);
1771 locked = VFS_LOCK_GIANT(cdir->v_mount);
1773 VFS_UNLOCK_GIANT(locked);
1776 locked = VFS_LOCK_GIANT(rdir->v_mount);
1778 VFS_UNLOCK_GIANT(locked);
1781 locked = VFS_LOCK_GIANT(jdir->v_mount);
1783 VFS_UNLOCK_GIANT(locked);
1790 * For setugid programs, we don't want to people to use that setugidness
1791 * to generate error messages which write to a file which otherwise would
1792 * otherwise be off-limits to the process. We check for filesystems where
1793 * the vnode can change out from under us after execve (like [lin]procfs).
1795 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1796 * sufficient. We also don't check for setugidness since we know we are.
1799 is_unsafe(struct file *fp)
1801 if (fp->f_type == DTYPE_VNODE) {
1802 struct vnode *vp = fp->f_vnode;
1804 if ((vp->v_vflag & VV_PROCDEP) != 0)
1811 * Make this setguid thing safe, if at all possible.
1814 setugidsafety(struct thread *td)
1816 struct filedesc *fdp;
1819 /* Certain daemons might not have file descriptors. */
1820 fdp = td->td_proc->p_fd;
1825 * Note: fdp->fd_ofiles may be reallocated out from under us while
1826 * we are blocked in a close. Be careful!
1828 FILEDESC_XLOCK(fdp);
1829 for (i = 0; i <= fdp->fd_lastfile; i++) {
1832 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1835 knote_fdclose(td, i);
1837 * NULL-out descriptor prior to close to avoid
1838 * a race while close blocks.
1840 fp = fdp->fd_ofiles[i];
1841 fdp->fd_ofiles[i] = NULL;
1842 fdp->fd_ofileflags[i] = 0;
1844 FILEDESC_XUNLOCK(fdp);
1845 (void) closef(fp, td);
1846 FILEDESC_XLOCK(fdp);
1849 FILEDESC_XUNLOCK(fdp);
1853 * If a specific file object occupies a specific file descriptor, close the
1854 * file descriptor entry and drop a reference on the file object. This is a
1855 * convenience function to handle a subsequent error in a function that calls
1856 * falloc() that handles the race that another thread might have closed the
1857 * file descriptor out from under the thread creating the file object.
1860 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1863 FILEDESC_XLOCK(fdp);
1864 if (fdp->fd_ofiles[idx] == fp) {
1865 fdp->fd_ofiles[idx] = NULL;
1867 FILEDESC_XUNLOCK(fdp);
1870 FILEDESC_XUNLOCK(fdp);
1874 * Close any files on exec?
1877 fdcloseexec(struct thread *td)
1879 struct filedesc *fdp;
1882 /* Certain daemons might not have file descriptors. */
1883 fdp = td->td_proc->p_fd;
1887 FILEDESC_XLOCK(fdp);
1890 * We cannot cache fd_ofiles or fd_ofileflags since operations
1891 * may block and rip them out from under us.
1893 for (i = 0; i <= fdp->fd_lastfile; i++) {
1894 if (fdp->fd_ofiles[i] != NULL &&
1895 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1896 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1899 knote_fdclose(td, i);
1901 * NULL-out descriptor prior to close to avoid
1902 * a race while close blocks.
1904 fp = fdp->fd_ofiles[i];
1905 fdp->fd_ofiles[i] = NULL;
1906 fdp->fd_ofileflags[i] = 0;
1908 if (fp->f_type == DTYPE_MQUEUE)
1909 mq_fdclose(td, i, fp);
1910 FILEDESC_XUNLOCK(fdp);
1911 (void) closef(fp, td);
1912 FILEDESC_XLOCK(fdp);
1915 FILEDESC_XUNLOCK(fdp);
1919 * It is unsafe for set[ug]id processes to be started with file
1920 * descriptors 0..2 closed, as these descriptors are given implicit
1921 * significance in the Standard C library. fdcheckstd() will create a
1922 * descriptor referencing /dev/null for each of stdin, stdout, and
1923 * stderr that is not already open.
1926 fdcheckstd(struct thread *td)
1928 struct filedesc *fdp;
1929 register_t retval, save;
1930 int i, error, devnull;
1932 fdp = td->td_proc->p_fd;
1935 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1938 for (i = 0; i < 3; i++) {
1939 if (fdp->fd_ofiles[i] != NULL)
1942 save = td->td_retval[0];
1943 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1945 devnull = td->td_retval[0];
1946 KASSERT(devnull == i, ("oof, we didn't get our fd"));
1947 td->td_retval[0] = save;
1951 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1960 * Internal form of close. Decrement reference count on file structure.
1961 * Note: td may be NULL when closing a file that was being passed in a
1964 * XXXRW: Giant is not required for the caller, but often will be held; this
1965 * makes it moderately likely the Giant will be recursed in the VFS case.
1968 closef(struct file *fp, struct thread *td)
1972 struct filedesc_to_leader *fdtol;
1973 struct filedesc *fdp;
1976 * POSIX record locking dictates that any close releases ALL
1977 * locks owned by this process. This is handled by setting
1978 * a flag in the unlock to free ONLY locks obeying POSIX
1979 * semantics, and not to free BSD-style file locks.
1980 * If the descriptor was in a message, POSIX-style locks
1981 * aren't passed with the descriptor, and the thread pointer
1982 * will be NULL. Callers should be careful only to pass a
1983 * NULL thread pointer when there really is no owning
1984 * context that might have locks, or the locks will be
1987 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1991 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1992 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1993 lf.l_whence = SEEK_SET;
1996 lf.l_type = F_UNLCK;
1997 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1998 F_UNLCK, &lf, F_POSIX);
2000 fdtol = td->td_proc->p_fdtol;
2001 if (fdtol != NULL) {
2003 * Handle special case where file descriptor table is
2004 * shared between multiple process leaders.
2006 fdp = td->td_proc->p_fd;
2007 FILEDESC_XLOCK(fdp);
2008 for (fdtol = fdtol->fdl_next;
2009 fdtol != td->td_proc->p_fdtol;
2010 fdtol = fdtol->fdl_next) {
2011 if ((fdtol->fdl_leader->p_flag &
2014 fdtol->fdl_holdcount++;
2015 FILEDESC_XUNLOCK(fdp);
2016 lf.l_whence = SEEK_SET;
2019 lf.l_type = F_UNLCK;
2021 (void) VOP_ADVLOCK(vp,
2022 (caddr_t)fdtol->fdl_leader,
2023 F_UNLCK, &lf, F_POSIX);
2024 FILEDESC_XLOCK(fdp);
2025 fdtol->fdl_holdcount--;
2026 if (fdtol->fdl_holdcount == 0 &&
2027 fdtol->fdl_wakeup != 0) {
2028 fdtol->fdl_wakeup = 0;
2032 FILEDESC_XUNLOCK(fdp);
2034 VFS_UNLOCK_GIANT(vfslocked);
2036 return (fdrop(fp, td));
2040 * Extract the file pointer associated with the specified descriptor for the
2041 * current user process.
2043 * If the descriptor doesn't exist, EBADF is returned.
2045 * If the descriptor exists but doesn't match 'flags' then return EBADF for
2046 * read attempts and EINVAL for write attempts.
2048 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
2049 * It should be dropped with fdrop(). If it is not set, then the refcount
2050 * will not be bumped however the thread's filedesc struct will be returned
2051 * locked (for fgetsock).
2053 * If an error occured the non-zero error is returned and *fpp is set to
2054 * NULL. Otherwise *fpp is set and zero is returned.
2057 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
2059 struct filedesc *fdp;
2063 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2065 FILEDESC_SLOCK(fdp);
2066 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
2067 FILEDESC_SUNLOCK(fdp);
2072 * FREAD and FWRITE failure return EBADF as per POSIX.
2074 * Only one flag, or 0, may be specified.
2076 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
2077 FILEDESC_SUNLOCK(fdp);
2080 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2081 FILEDESC_SUNLOCK(fdp);
2086 FILEDESC_SUNLOCK(fdp);
2093 fget(struct thread *td, int fd, struct file **fpp)
2096 return(_fget(td, fd, fpp, 0, 1));
2100 fget_read(struct thread *td, int fd, struct file **fpp)
2103 return(_fget(td, fd, fpp, FREAD, 1));
2107 fget_write(struct thread *td, int fd, struct file **fpp)
2110 return(_fget(td, fd, fpp, FWRITE, 1));
2114 * Like fget() but loads the underlying vnode, or returns an error if the
2115 * descriptor does not represent a vnode. Note that pipes use vnodes but
2116 * never have VM objects. The returned vnode will be vref()'d.
2118 * XXX: what about the unused flags ?
2121 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2127 if ((error = _fget(td, fd, &fp, flags, 0)) != 0)
2129 if (fp->f_vnode == NULL) {
2135 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2140 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2143 return (_fgetvp(td, fd, vpp, 0));
2147 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2150 return (_fgetvp(td, fd, vpp, FREAD));
2155 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2158 return (_fgetvp(td, fd, vpp, FWRITE));
2163 * Like fget() but loads the underlying socket, or returns an error if the
2164 * descriptor does not represent a socket.
2166 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2169 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2170 * on their file descriptor reference to prevent the socket from being free'd
2174 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2182 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2184 if (fp->f_type != DTYPE_SOCKET) {
2189 *fflagp = fp->f_flag;
2194 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2199 * Drop the reference count on the socket and XXX release the SX lock in the
2200 * future. The last reference closes the socket.
2202 * Note: fputsock() is deprecated, see comment for fgetsock().
2205 fputsock(struct socket *so)
2214 fdrop(struct file *fp, struct thread *td)
2218 return (fdrop_locked(fp, td));
2222 * Drop reference on struct file passed in, may call closef if the
2223 * reference hits zero.
2224 * Expects struct file locked, and will unlock it.
2227 fdrop_locked(struct file *fp, struct thread *td)
2231 FILE_LOCK_ASSERT(fp, MA_OWNED);
2233 if (--fp->f_count > 0) {
2239 * We might have just dropped the last reference to a file
2240 * object that is for a UNIX domain socket whose message
2241 * buffers are being examined in unp_gc(). If that is the
2242 * case, FWAIT will be set in f_gcflag and we need to wait for
2243 * unp_gc() to finish its scan.
2245 while (fp->f_gcflag & FWAIT)
2246 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2248 /* We have the last ref so we can proceed without the file lock. */
2250 if (fp->f_count < 0)
2251 panic("fdrop: count < 0");
2252 if (fp->f_ops != &badfileops)
2253 error = fo_close(fp, td);
2257 sx_xlock(&filelist_lock);
2258 LIST_REMOVE(fp, f_list);
2260 sx_xunlock(&filelist_lock);
2263 * The f_cdevpriv cannot be assigned non-NULL value while we
2264 * are destroying the file.
2266 if (fp->f_cdevpriv != NULL)
2269 uma_zfree(file_zone, fp);
2275 * Apply an advisory lock on a file descriptor.
2277 * Just attempt to get a record lock of the requested type on the entire file
2278 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2280 #ifndef _SYS_SYSPROTO_H_
2288 flock(struct thread *td, struct flock_args *uap)
2296 if ((error = fget(td, uap->fd, &fp)) != 0)
2298 if (fp->f_type != DTYPE_VNODE) {
2300 return (EOPNOTSUPP);
2304 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2305 lf.l_whence = SEEK_SET;
2308 if (uap->how & LOCK_UN) {
2309 lf.l_type = F_UNLCK;
2311 fp->f_flag &= ~FHASLOCK;
2313 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2316 if (uap->how & LOCK_EX)
2317 lf.l_type = F_WRLCK;
2318 else if (uap->how & LOCK_SH)
2319 lf.l_type = F_RDLCK;
2325 fp->f_flag |= FHASLOCK;
2327 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2328 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2331 VFS_UNLOCK_GIANT(vfslocked);
2335 * Duplicate the specified descriptor to a free descriptor.
2338 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2344 * If the to-be-dup'd fd number is greater than the allowed number
2345 * of file descriptors, or the fd to be dup'd has already been
2346 * closed, then reject.
2348 FILEDESC_XLOCK(fdp);
2349 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2350 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2351 FILEDESC_XUNLOCK(fdp);
2356 * There are two cases of interest here.
2358 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2360 * For ENXIO steal away the file structure from (dfd) and store it in
2361 * (indx). (dfd) is effectively closed by this operation.
2363 * Any other error code is just returned.
2368 * Check that the mode the file is being opened for is a
2369 * subset of the mode of the existing descriptor.
2372 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2374 FILEDESC_XUNLOCK(fdp);
2377 fp = fdp->fd_ofiles[indx];
2378 fdp->fd_ofiles[indx] = wfp;
2379 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2384 FILEDESC_XUNLOCK(fdp);
2387 * We now own the reference to fp that the ofiles[]
2388 * array used to own. Release it.
2395 * Steal away the file pointer from dfd and stuff it into indx.
2397 fp = fdp->fd_ofiles[indx];
2398 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2399 fdp->fd_ofiles[dfd] = NULL;
2400 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2401 fdp->fd_ofileflags[dfd] = 0;
2405 FILEDESC_XUNLOCK(fdp);
2408 * We now own the reference to fp that the ofiles[] array
2409 * used to own. Release it.
2416 FILEDESC_XUNLOCK(fdp);
2423 * Scan all active processes to see if any of them have a current or root
2424 * directory of `olddp'. If so, replace them with the new mount point.
2427 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2429 struct filedesc *fdp;
2433 if (vrefcnt(olddp) == 1)
2435 sx_slock(&allproc_lock);
2436 FOREACH_PROC_IN_SYSTEM(p) {
2441 FILEDESC_XLOCK(fdp);
2442 if (fdp->fd_cdir == olddp) {
2444 fdp->fd_cdir = newdp;
2447 if (fdp->fd_rdir == olddp) {
2449 fdp->fd_rdir = newdp;
2452 FILEDESC_XUNLOCK(fdp);
2457 sx_sunlock(&allproc_lock);
2458 if (rootvnode == olddp) {
2465 struct filedesc_to_leader *
2466 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2468 struct filedesc_to_leader *fdtol;
2470 MALLOC(fdtol, struct filedesc_to_leader *,
2471 sizeof(struct filedesc_to_leader),
2472 M_FILEDESC_TO_LEADER,
2474 fdtol->fdl_refcount = 1;
2475 fdtol->fdl_holdcount = 0;
2476 fdtol->fdl_wakeup = 0;
2477 fdtol->fdl_leader = leader;
2479 FILEDESC_XLOCK(fdp);
2480 fdtol->fdl_next = old->fdl_next;
2481 fdtol->fdl_prev = old;
2482 old->fdl_next = fdtol;
2483 fdtol->fdl_next->fdl_prev = fdtol;
2484 FILEDESC_XUNLOCK(fdp);
2486 fdtol->fdl_next = fdtol;
2487 fdtol->fdl_prev = fdtol;
2493 * Get file structures globally.
2496 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2499 struct filedesc *fdp;
2505 * Note: because the number of file descriptors is calculated
2506 * in different ways for sizing vs returning the data,
2507 * there is information leakage from the first loop. However,
2508 * it is of a similar order of magnitude to the leakage from
2509 * global system statistics such as kern.openfiles.
2511 error = sysctl_wire_old_buffer(req, 0);
2514 if (req->oldptr == NULL) {
2515 n = 16; /* A slight overestimate. */
2516 sx_slock(&filelist_lock);
2517 LIST_FOREACH(fp, &filehead, f_list) {
2519 * We should grab the lock, but this is an
2520 * estimate, so does it really matter?
2522 /* mtx_lock(fp->f_mtxp); */
2524 /* mtx_unlock(f->f_mtxp); */
2526 sx_sunlock(&filelist_lock);
2527 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2530 bzero(&xf, sizeof(xf));
2531 xf.xf_size = sizeof(xf);
2532 sx_slock(&allproc_lock);
2533 FOREACH_PROC_IN_SYSTEM(p) {
2534 if (p->p_state == PRS_NEW)
2537 if (p_cansee(req->td, p) != 0) {
2541 xf.xf_pid = p->p_pid;
2542 xf.xf_uid = p->p_ucred->cr_uid;
2547 FILEDESC_SLOCK(fdp);
2548 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2549 if ((fp = fdp->fd_ofiles[n]) == NULL)
2553 xf.xf_data = fp->f_data;
2554 xf.xf_vnode = fp->f_vnode;
2555 xf.xf_type = fp->f_type;
2556 xf.xf_count = fp->f_count;
2557 xf.xf_msgcount = fp->f_msgcount;
2558 xf.xf_offset = fp->f_offset;
2559 xf.xf_flag = fp->f_flag;
2560 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2564 FILEDESC_SUNLOCK(fdp);
2569 sx_sunlock(&allproc_lock);
2573 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2574 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2576 #ifdef KINFO_OFILE_SIZE
2577 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2580 /* Compatability with early 7-stable */
2582 export_vnode_for_osysctl(struct vnode *vp, int type,
2583 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2586 char *fullpath, *freepath;
2589 bzero(kif, sizeof(*kif));
2590 kif->kf_structsize = sizeof(*kif);
2594 kif->kf_type = KF_TYPE_VNODE;
2595 /* This function only handles directories. */
2596 KASSERT(vp->v_type == VDIR, ("export_vnode_for_osysctl: vnode not directory"));
2597 kif->kf_vnode_type = KF_VTYPE_VDIR;
2600 * This is not a true file descriptor, so we set a bogus refcount
2601 * and offset to indicate these fields should be ignored.
2603 kif->kf_ref_count = -1;
2604 kif->kf_offset = -1;
2608 FILEDESC_SUNLOCK(fdp);
2609 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2610 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
2611 vn_fullpath(curthread, vp, &fullpath, &freepath);
2613 VFS_UNLOCK_GIANT(vfslocked);
2614 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2615 if (freepath != NULL)
2616 free(freepath, M_TEMP);
2617 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2618 FILEDESC_SLOCK(fdp);
2623 * Get per-process file descriptors for use by procstat(1), et al.
2626 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2628 char *fullpath, *freepath;
2629 struct kinfo_ofile *kif;
2630 struct filedesc *fdp;
2631 int error, i, *name;
2639 if ((p = pfind((pid_t)name[0])) == NULL)
2641 if ((error = p_candebug(curthread, p))) {
2649 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2650 FILEDESC_SLOCK(fdp);
2651 if (fdp->fd_cdir != NULL)
2652 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2654 if (fdp->fd_rdir != NULL)
2655 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2657 if (fdp->fd_jdir != NULL)
2658 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2660 for (i = 0; i < fdp->fd_nfiles; i++) {
2661 if ((fp = fdp->fd_ofiles[i]) == NULL)
2663 bzero(kif, sizeof(*kif));
2664 kif->kf_structsize = sizeof(*kif);
2669 switch (fp->f_type) {
2671 kif->kf_type = KF_TYPE_VNODE;
2677 kif->kf_type = KF_TYPE_SOCKET;
2682 kif->kf_type = KF_TYPE_PIPE;
2686 kif->kf_type = KF_TYPE_FIFO;
2692 kif->kf_type = KF_TYPE_KQUEUE;
2696 kif->kf_type = KF_TYPE_CRYPTO;
2700 kif->kf_type = KF_TYPE_MQUEUE;
2704 kif->kf_type = KF_TYPE_UNKNOWN;
2707 kif->kf_ref_count = fp->f_count;
2708 if (fp->f_flag & FREAD)
2709 kif->kf_flags |= KF_FLAG_READ;
2710 if (fp->f_flag & FWRITE)
2711 kif->kf_flags |= KF_FLAG_WRITE;
2712 if (fp->f_flag & FAPPEND)
2713 kif->kf_flags |= KF_FLAG_APPEND;
2714 if (fp->f_flag & FASYNC)
2715 kif->kf_flags |= KF_FLAG_ASYNC;
2716 if (fp->f_flag & FFSYNC)
2717 kif->kf_flags |= KF_FLAG_FSYNC;
2718 if (fp->f_flag & FNONBLOCK)
2719 kif->kf_flags |= KF_FLAG_NONBLOCK;
2720 if (fp->f_flag & O_DIRECT)
2721 kif->kf_flags |= KF_FLAG_DIRECT;
2722 if (fp->f_flag & FHASLOCK)
2723 kif->kf_flags |= KF_FLAG_HASLOCK;
2724 kif->kf_offset = fp->f_offset;
2727 switch (vp->v_type) {
2729 kif->kf_vnode_type = KF_VTYPE_VNON;
2732 kif->kf_vnode_type = KF_VTYPE_VREG;
2735 kif->kf_vnode_type = KF_VTYPE_VDIR;
2738 kif->kf_vnode_type = KF_VTYPE_VBLK;
2741 kif->kf_vnode_type = KF_VTYPE_VCHR;
2744 kif->kf_vnode_type = KF_VTYPE_VLNK;
2747 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2750 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2753 kif->kf_vnode_type = KF_VTYPE_VBAD;
2756 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2760 * It is OK to drop the filedesc lock here as we will
2761 * re-validate and re-evaluate its properties when
2762 * the loop continues.
2766 FILEDESC_SUNLOCK(fdp);
2767 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2768 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
2769 vn_fullpath(curthread, vp, &fullpath, &freepath);
2771 VFS_UNLOCK_GIANT(vfslocked);
2772 strlcpy(kif->kf_path, fullpath,
2773 sizeof(kif->kf_path));
2774 if (freepath != NULL)
2775 free(freepath, M_TEMP);
2776 FILEDESC_SLOCK(fdp);
2779 struct sockaddr *sa;
2781 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2782 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2783 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2786 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2787 == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2788 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2791 kif->kf_sock_domain =
2792 so->so_proto->pr_domain->dom_family;
2793 kif->kf_sock_type = so->so_type;
2794 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2796 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2800 FILEDESC_SUNLOCK(fdp);
2806 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2807 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2809 #ifdef KINFO_FILE_SIZE
2810 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2814 export_vnode_for_sysctl(struct vnode *vp, int type,
2815 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2818 char *fullpath, *freepath;
2821 bzero(kif, sizeof(*kif));
2825 kif->kf_type = KF_TYPE_VNODE;
2826 /* This function only handles directories. */
2827 KASSERT(vp->v_type == VDIR, ("export_vnode_for_sysctl: vnode not directory"));
2828 kif->kf_vnode_type = KF_VTYPE_VDIR;
2831 * This is not a true file descriptor, so we set a bogus refcount
2832 * and offset to indicate these fields should be ignored.
2834 kif->kf_ref_count = -1;
2835 kif->kf_offset = -1;
2839 FILEDESC_SUNLOCK(fdp);
2840 vn_fullpath(curthread, vp, &fullpath, &freepath);
2841 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2843 VFS_UNLOCK_GIANT(vfslocked);
2844 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2845 if (freepath != NULL)
2846 free(freepath, M_TEMP);
2847 /* Pack record size down */
2848 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2849 strlen(kif->kf_path) + 1;
2850 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2851 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2852 FILEDESC_SLOCK(fdp);
2857 * Get per-process file descriptors for use by procstat(1), et al.
2860 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2862 char *fullpath, *freepath;
2863 struct kinfo_file *kif;
2864 struct filedesc *fdp;
2865 int error, i, *name;
2873 if ((p = pfind((pid_t)name[0])) == NULL)
2875 if ((error = p_candebug(curthread, p))) {
2883 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2884 FILEDESC_SLOCK(fdp);
2885 if (fdp->fd_cdir != NULL)
2886 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2888 if (fdp->fd_rdir != NULL)
2889 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2891 if (fdp->fd_jdir != NULL)
2892 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2894 for (i = 0; i < fdp->fd_nfiles; i++) {
2895 if ((fp = fdp->fd_ofiles[i]) == NULL)
2897 bzero(kif, sizeof(*kif));
2902 switch (fp->f_type) {
2904 kif->kf_type = KF_TYPE_VNODE;
2910 kif->kf_type = KF_TYPE_SOCKET;
2915 kif->kf_type = KF_TYPE_PIPE;
2919 kif->kf_type = KF_TYPE_FIFO;
2925 kif->kf_type = KF_TYPE_KQUEUE;
2929 kif->kf_type = KF_TYPE_CRYPTO;
2933 kif->kf_type = KF_TYPE_MQUEUE;
2937 kif->kf_type = KF_TYPE_SEM;
2941 kif->kf_type = KF_TYPE_UNKNOWN;
2944 kif->kf_ref_count = fp->f_count;
2945 if (fp->f_flag & FREAD)
2946 kif->kf_flags |= KF_FLAG_READ;
2947 if (fp->f_flag & FWRITE)
2948 kif->kf_flags |= KF_FLAG_WRITE;
2949 if (fp->f_flag & FAPPEND)
2950 kif->kf_flags |= KF_FLAG_APPEND;
2951 if (fp->f_flag & FASYNC)
2952 kif->kf_flags |= KF_FLAG_ASYNC;
2953 if (fp->f_flag & FFSYNC)
2954 kif->kf_flags |= KF_FLAG_FSYNC;
2955 if (fp->f_flag & FNONBLOCK)
2956 kif->kf_flags |= KF_FLAG_NONBLOCK;
2957 if (fp->f_flag & O_DIRECT)
2958 kif->kf_flags |= KF_FLAG_DIRECT;
2959 if (fp->f_flag & FHASLOCK)
2960 kif->kf_flags |= KF_FLAG_HASLOCK;
2961 kif->kf_offset = fp->f_offset;
2964 switch (vp->v_type) {
2966 kif->kf_vnode_type = KF_VTYPE_VNON;
2969 kif->kf_vnode_type = KF_VTYPE_VREG;
2972 kif->kf_vnode_type = KF_VTYPE_VDIR;
2975 kif->kf_vnode_type = KF_VTYPE_VBLK;
2978 kif->kf_vnode_type = KF_VTYPE_VCHR;
2981 kif->kf_vnode_type = KF_VTYPE_VLNK;
2984 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2987 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2990 kif->kf_vnode_type = KF_VTYPE_VBAD;
2993 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2997 * It is OK to drop the filedesc lock here as we will
2998 * re-validate and re-evaluate its properties when
2999 * the loop continues.
3003 FILEDESC_SUNLOCK(fdp);
3004 vn_fullpath(curthread, vp, &fullpath, &freepath);
3005 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3007 VFS_UNLOCK_GIANT(vfslocked);
3008 strlcpy(kif->kf_path, fullpath,
3009 sizeof(kif->kf_path));
3010 if (freepath != NULL)
3011 free(freepath, M_TEMP);
3012 FILEDESC_SLOCK(fdp);
3015 struct sockaddr *sa;
3017 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3018 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3019 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3022 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3023 == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3024 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3027 kif->kf_sock_domain =
3028 so->so_proto->pr_domain->dom_family;
3029 kif->kf_sock_type = so->so_type;
3030 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3032 /* Pack record size down */
3033 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3034 strlen(kif->kf_path) + 1;
3035 kif->kf_structsize = roundup(kif->kf_structsize,
3037 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3041 FILEDESC_SUNLOCK(fdp);
3047 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3048 sysctl_kern_proc_filedesc, "Process filedesc entries");
3052 * For the purposes of debugging, generate a human-readable string for the
3056 file_type_to_name(short type)
3084 * For the purposes of debugging, identify a process (if any, perhaps one of
3085 * many) that references the passed file in its file descriptor array. Return
3088 static struct proc *
3089 file_to_first_proc(struct file *fp)
3091 struct filedesc *fdp;
3095 FOREACH_PROC_IN_SYSTEM(p) {
3096 if (p->p_state == PRS_NEW)
3101 for (n = 0; n < fdp->fd_nfiles; n++) {
3102 if (fp == fdp->fd_ofiles[n])
3110 db_print_file(struct file *fp, int header)
3115 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3116 "File", "Type", "Data", "Flag", "GCFl", "Count",
3117 "MCount", "Vnode", "FPID", "FCmd");
3118 p = file_to_first_proc(fp);
3119 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3120 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3121 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
3122 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3125 DB_SHOW_COMMAND(file, db_show_file)
3130 db_printf("usage: show file <addr>\n");
3133 fp = (struct file *)addr;
3134 db_print_file(fp, 1);
3137 DB_SHOW_COMMAND(files, db_show_files)
3143 LIST_FOREACH(fp, &filehead, f_list) {
3144 db_print_file(fp, header);
3150 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3151 &maxfilesperproc, 0, "Maximum files allowed open per process");
3153 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3154 &maxfiles, 0, "Maximum number of files");
3156 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3157 &openfiles, 0, "System-wide number of open files");
3161 filelistinit(void *dummy)
3164 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3165 NULL, NULL, UMA_ALIGN_PTR, 0);
3166 sx_init(&filelist_lock, "filelist lock");
3167 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3168 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3170 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3172 /*-------------------------------------------------------------------*/
3175 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3182 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3189 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3196 badfo_kqfilter(struct file *fp, struct knote *kn)
3203 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3210 badfo_close(struct file *fp, struct thread *td)
3216 struct fileops badfileops = {
3217 .fo_read = badfo_readwrite,
3218 .fo_write = badfo_readwrite,
3219 .fo_ioctl = badfo_ioctl,
3220 .fo_poll = badfo_poll,
3221 .fo_kqfilter = badfo_kqfilter,
3222 .fo_stat = badfo_stat,
3223 .fo_close = badfo_close,
3227 /*-------------------------------------------------------------------*/
3230 * File Descriptor pseudo-device driver (/dev/fd/).
3232 * Opening minor device N dup()s the file (if any) connected to file
3233 * descriptor N belonging to the calling process. Note that this driver
3234 * consists of only the ``open()'' routine, because all subsequent
3235 * references to this file will be direct to the other driver.
3237 * XXX: we could give this one a cloning event handler if necessary.
3242 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3246 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3247 * the file descriptor being sought for duplication. The error
3248 * return ensures that the vnode for this device will be released
3249 * by vn_open. Open will detect this special error and take the
3250 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3251 * will simply report the error.
3253 td->td_dupfd = dev2unit(dev);
3257 static struct cdevsw fildesc_cdevsw = {
3258 .d_version = D_VERSION,
3259 .d_flags = D_NEEDGIANT,
3265 fildesc_drvinit(void *unused)
3269 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
3270 make_dev_alias(dev, "stdin");
3271 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
3272 make_dev_alias(dev, "stdout");
3273 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
3274 make_dev_alias(dev, "stderr");
3277 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);