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>
74 #include <sys/unistd.h>
76 #include <sys/vnode.h>
78 #include <sys/ktrace.h>
81 #include <security/audit/audit.h>
87 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
88 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
89 "file desc to leader structures");
90 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
92 static uma_zone_t file_zone;
95 /* Flags for do_dup() */
96 #define DUP_FIXED 0x1 /* Force fixed allocation */
97 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
99 static int do_dup(struct thread *td, int flags, int old, int new,
101 static int fd_first_free(struct filedesc *, int, int);
102 static int fd_last_used(struct filedesc *, int, int);
103 static void fdgrowtable(struct filedesc *, int);
104 static void fdunused(struct filedesc *fdp, int fd);
105 static void fdused(struct filedesc *fdp, int fd);
108 * A process is initially started out with NDFILE descriptors stored within
109 * this structure, selected to be enough for typical applications based on
110 * the historical limit of 20 open files (and the usage of descriptors by
111 * shells). If these descriptors are exhausted, a larger descriptor table
112 * may be allocated, up to a process' resource limit; the internal arrays
116 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
117 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
118 #define NDSLOT(x) ((x) / NDENTRIES)
119 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
120 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
123 * Storage required per open file descriptor.
125 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
128 * Storage to hold unused ofiles that need to be reclaimed.
131 struct file **ft_table;
132 SLIST_ENTRY(freetable) ft_next;
136 * Basic allocation of descriptors:
137 * one of the above, plus arrays for NDFILE descriptors.
140 struct filedesc fd_fd;
142 * ofiles which need to be reclaimed on free.
144 SLIST_HEAD(,freetable) fd_free;
146 * These arrays are used when the number of open files is
147 * <= NDFILE, and are then pointed to by the pointers above.
149 struct file *fd_dfiles[NDFILE];
150 char fd_dfileflags[NDFILE];
151 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
155 * Descriptor management.
157 volatile int openfiles; /* actual number of open files */
158 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
159 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
161 /* A mutex to protect the association between a proc and filedesc. */
162 static struct mtx fdesc_mtx;
165 * Find the first zero bit in the given bitmap, starting at low and not
166 * exceeding size - 1.
169 fd_first_free(struct filedesc *fdp, int low, int size)
171 NDSLOTTYPE *map = fdp->fd_map;
179 if (low % NDENTRIES) {
180 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
181 if ((mask &= ~map[off]) != 0UL)
182 return (off * NDENTRIES + ffsl(mask) - 1);
185 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
186 if (map[off] != ~0UL)
187 return (off * NDENTRIES + ffsl(~map[off]) - 1);
192 * Find the highest non-zero bit in the given bitmap, starting at low and
193 * not exceeding size - 1.
196 fd_last_used(struct filedesc *fdp, int low, int size)
198 NDSLOTTYPE *map = fdp->fd_map;
206 if (size % NDENTRIES) {
207 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
208 if ((mask &= map[off]) != 0)
209 return (off * NDENTRIES + flsl(mask) - 1);
212 for (minoff = NDSLOT(low); off >= minoff; --off)
214 return (off * NDENTRIES + flsl(map[off]) - 1);
219 fdisused(struct filedesc *fdp, int fd)
221 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
222 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
223 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
227 * Mark a file descriptor as used.
230 fdused(struct filedesc *fdp, int fd)
233 FILEDESC_XLOCK_ASSERT(fdp);
234 KASSERT(!fdisused(fdp, fd),
235 ("fd already used"));
237 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
238 if (fd > fdp->fd_lastfile)
239 fdp->fd_lastfile = fd;
240 if (fd == fdp->fd_freefile)
241 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
245 * Mark a file descriptor as unused.
248 fdunused(struct filedesc *fdp, int fd)
251 FILEDESC_XLOCK_ASSERT(fdp);
252 KASSERT(fdisused(fdp, fd),
253 ("fd is already unused"));
254 KASSERT(fdp->fd_ofiles[fd] == NULL,
255 ("fd is still in use"));
257 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
258 if (fd < fdp->fd_freefile)
259 fdp->fd_freefile = fd;
260 if (fd == fdp->fd_lastfile)
261 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
265 * System calls on descriptors.
267 #ifndef _SYS_SYSPROTO_H_
268 struct getdtablesize_args {
274 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
276 struct proc *p = td->td_proc;
280 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
286 * Duplicate a file descriptor to a particular value.
288 * Note: keep in mind that a potential race condition exists when closing
289 * descriptors from a shared descriptor table (via rfork).
291 #ifndef _SYS_SYSPROTO_H_
299 dup2(struct thread *td, struct dup2_args *uap)
302 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
307 * Duplicate a file descriptor.
309 #ifndef _SYS_SYSPROTO_H_
316 dup(struct thread *td, struct dup_args *uap)
319 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
323 * The file control system call.
325 #ifndef _SYS_SYSPROTO_H_
334 fcntl(struct thread *td, struct fcntl_args *uap)
349 * Convert old flock structure to new.
351 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
352 fl.l_start = ofl.l_start;
353 fl.l_len = ofl.l_len;
354 fl.l_pid = ofl.l_pid;
355 fl.l_type = ofl.l_type;
356 fl.l_whence = ofl.l_whence;
376 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
385 error = kern_fcntl(td, uap->fd, cmd, arg);
388 if (uap->cmd == F_OGETLK) {
389 ofl.l_start = fl.l_start;
390 ofl.l_len = fl.l_len;
391 ofl.l_pid = fl.l_pid;
392 ofl.l_type = fl.l_type;
393 ofl.l_whence = fl.l_whence;
394 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
395 } else if (uap->cmd == F_GETLK) {
396 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
401 static inline struct file *
402 fdtofp(int fd, struct filedesc *fdp)
406 FILEDESC_LOCK_ASSERT(fdp);
407 if ((unsigned)fd >= fdp->fd_nfiles ||
408 (fp = fdp->fd_ofiles[fd]) == NULL)
414 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
416 struct filedesc *fdp;
434 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
439 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
444 if ((fp = fdtofp(fd, fdp)) == NULL) {
445 FILEDESC_SUNLOCK(fdp);
449 pop = &fdp->fd_ofileflags[fd];
450 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
451 FILEDESC_SUNLOCK(fdp);
456 if ((fp = fdtofp(fd, fdp)) == NULL) {
457 FILEDESC_XUNLOCK(fdp);
461 pop = &fdp->fd_ofileflags[fd];
462 *pop = (*pop &~ UF_EXCLOSE) |
463 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
464 FILEDESC_XUNLOCK(fdp);
469 if ((fp = fdtofp(fd, fdp)) == NULL) {
470 FILEDESC_SUNLOCK(fdp);
474 td->td_retval[0] = OFLAGS(fp->f_flag);
475 FILEDESC_SUNLOCK(fdp);
480 if ((fp = fdtofp(fd, fdp)) == NULL) {
481 FILEDESC_SUNLOCK(fdp);
486 FILEDESC_SUNLOCK(fdp);
488 tmp = flg = fp->f_flag;
490 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
491 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
492 tmp = fp->f_flag & FNONBLOCK;
493 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
498 tmp = fp->f_flag & FASYNC;
499 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
504 atomic_clear_int(&fp->f_flag, FNONBLOCK);
506 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
512 if ((fp = fdtofp(fd, fdp)) == NULL) {
513 FILEDESC_SUNLOCK(fdp);
518 FILEDESC_SUNLOCK(fdp);
519 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
521 td->td_retval[0] = tmp;
527 if ((fp = fdtofp(fd, fdp)) == NULL) {
528 FILEDESC_SUNLOCK(fdp);
533 FILEDESC_SUNLOCK(fdp);
535 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
540 error = priv_check(td, PRIV_NFS_LOCKD);
548 /* FALLTHROUGH F_SETLK */
553 if ((fp = fdtofp(fd, fdp)) == NULL) {
554 FILEDESC_SUNLOCK(fdp);
558 if (fp->f_type != DTYPE_VNODE) {
559 FILEDESC_SUNLOCK(fdp);
563 flp = (struct flock *)arg;
564 if (flp->l_whence == SEEK_CUR) {
565 if (fp->f_offset < 0 ||
567 fp->f_offset > OFF_MAX - flp->l_start)) {
568 FILEDESC_SUNLOCK(fdp);
572 flp->l_start += fp->f_offset;
576 * VOP_ADVLOCK() may block.
579 FILEDESC_SUNLOCK(fdp);
581 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
582 switch (flp->l_type) {
584 if ((fp->f_flag & FREAD) == 0) {
588 PROC_LOCK(p->p_leader);
589 p->p_leader->p_flag |= P_ADVLOCK;
590 PROC_UNLOCK(p->p_leader);
591 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
595 if ((fp->f_flag & FWRITE) == 0) {
599 PROC_LOCK(p->p_leader);
600 p->p_leader->p_flag |= P_ADVLOCK;
601 PROC_UNLOCK(p->p_leader);
602 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
606 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
611 * Temporary api for testing remote lock
614 if (flg != F_REMOTE) {
618 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
619 F_UNLCKSYS, flp, flg);
625 VFS_UNLOCK_GIANT(vfslocked);
627 /* Check for race with close */
629 if ((unsigned) fd >= fdp->fd_nfiles ||
630 fp != fdp->fd_ofiles[fd]) {
631 FILEDESC_SUNLOCK(fdp);
632 flp->l_whence = SEEK_SET;
635 flp->l_type = F_UNLCK;
636 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
637 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
638 F_UNLCK, flp, F_POSIX);
639 VFS_UNLOCK_GIANT(vfslocked);
642 FILEDESC_SUNLOCK(fdp);
648 if ((fp = fdtofp(fd, fdp)) == NULL) {
649 FILEDESC_SUNLOCK(fdp);
653 if (fp->f_type != DTYPE_VNODE) {
654 FILEDESC_SUNLOCK(fdp);
658 flp = (struct flock *)arg;
659 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
660 flp->l_type != F_UNLCK) {
661 FILEDESC_SUNLOCK(fdp);
665 if (flp->l_whence == SEEK_CUR) {
666 if ((flp->l_start > 0 &&
667 fp->f_offset > OFF_MAX - flp->l_start) ||
669 fp->f_offset < OFF_MIN - flp->l_start)) {
670 FILEDESC_SUNLOCK(fdp);
674 flp->l_start += fp->f_offset;
677 * VOP_ADVLOCK() may block.
680 FILEDESC_SUNLOCK(fdp);
682 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
683 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
685 VFS_UNLOCK_GIANT(vfslocked);
693 VFS_UNLOCK_GIANT(vfslocked);
698 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
701 do_dup(struct thread *td, int flags, int old, int new,
704 struct filedesc *fdp;
708 int error, holdleaders, maxfd;
714 * Verify we have a valid descriptor to dup from and possibly to
715 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
716 * return EINVAL when the new descriptor is out of bounds.
721 return (flags & DUP_FCNTL ? EINVAL : EBADF);
723 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
726 return (flags & DUP_FCNTL ? EINVAL : EMFILE);
729 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
730 FILEDESC_XUNLOCK(fdp);
733 if (flags & DUP_FIXED && old == new) {
735 FILEDESC_XUNLOCK(fdp);
738 fp = fdp->fd_ofiles[old];
742 * If the caller specified a file descriptor, make sure the file
743 * table is large enough to hold it, and grab it. Otherwise, just
744 * allocate a new descriptor the usual way. Since the filedesc
745 * lock may be temporarily dropped in the process, we have to look
748 if (flags & DUP_FIXED) {
749 if (new >= fdp->fd_nfiles)
750 fdgrowtable(fdp, new + 1);
751 if (fdp->fd_ofiles[new] == NULL)
754 if ((error = fdalloc(td, new, &new)) != 0) {
755 FILEDESC_XUNLOCK(fdp);
762 * If the old file changed out from under us then treat it as a
763 * bad file descriptor. Userland should do its own locking to
766 if (fdp->fd_ofiles[old] != fp) {
767 /* we've allocated a descriptor which we won't use */
768 if (fdp->fd_ofiles[new] == NULL)
770 FILEDESC_XUNLOCK(fdp);
775 ("new fd is same as old"));
778 * Save info on the descriptor being overwritten. We cannot close
779 * it without introducing an ownership race for the slot, since we
780 * need to drop the filedesc lock to call closef().
782 * XXX this duplicates parts of close().
784 delfp = fdp->fd_ofiles[new];
787 if (td->td_proc->p_fdtol != NULL) {
789 * Ask fdfree() to sleep to ensure that all relevant
790 * process leaders can be traversed in closef().
792 fdp->fd_holdleaderscount++;
798 * Duplicate the source descriptor
800 fdp->fd_ofiles[new] = fp;
801 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
802 if (new > fdp->fd_lastfile)
803 fdp->fd_lastfile = new;
807 * If we dup'd over a valid file, we now own the reference to it
808 * and must dispose of it using closef() semantics (as if a
809 * close() were performed on it).
811 * XXX this duplicates parts of close().
814 knote_fdclose(td, new);
815 if (delfp->f_type == DTYPE_MQUEUE)
816 mq_fdclose(td, new, delfp);
817 FILEDESC_XUNLOCK(fdp);
818 (void) closef(delfp, td);
821 fdp->fd_holdleaderscount--;
822 if (fdp->fd_holdleaderscount == 0 &&
823 fdp->fd_holdleaderswakeup != 0) {
824 fdp->fd_holdleaderswakeup = 0;
825 wakeup(&fdp->fd_holdleaderscount);
827 FILEDESC_XUNLOCK(fdp);
830 FILEDESC_XUNLOCK(fdp);
836 * If sigio is on the list associated with a process or process group,
837 * disable signalling from the device, remove sigio from the list and
841 funsetown(struct sigio **sigiop)
851 *(sigio->sio_myref) = NULL;
852 if ((sigio)->sio_pgid < 0) {
853 struct pgrp *pg = (sigio)->sio_pgrp;
855 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
859 struct proc *p = (sigio)->sio_proc;
861 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
866 crfree(sigio->sio_ucred);
867 free(sigio, M_SIGIO);
871 * Free a list of sigio structures.
872 * We only need to lock the SIGIO_LOCK because we have made ourselves
873 * inaccessible to callers of fsetown and therefore do not need to lock
874 * the proc or pgrp struct for the list manipulation.
877 funsetownlst(struct sigiolst *sigiolst)
883 sigio = SLIST_FIRST(sigiolst);
890 * Every entry of the list should belong
891 * to a single proc or pgrp.
893 if (sigio->sio_pgid < 0) {
894 pg = sigio->sio_pgrp;
895 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
896 } else /* if (sigio->sio_pgid > 0) */ {
898 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
902 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
903 *(sigio->sio_myref) = NULL;
905 KASSERT(sigio->sio_pgid < 0,
906 ("Proc sigio in pgrp sigio list"));
907 KASSERT(sigio->sio_pgrp == pg,
908 ("Bogus pgrp in sigio list"));
910 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
913 } else /* if (p != NULL) */ {
914 KASSERT(sigio->sio_pgid > 0,
915 ("Pgrp sigio in proc sigio list"));
916 KASSERT(sigio->sio_proc == p,
917 ("Bogus proc in sigio list"));
919 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
924 crfree(sigio->sio_ucred);
925 free(sigio, M_SIGIO);
932 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
934 * After permission checking, add a sigio structure to the sigio list for
935 * the process or process group.
938 fsetown(pid_t pgid, struct sigio **sigiop)
952 /* Allocate and fill in the new sigio out of locks. */
953 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
954 sigio->sio_pgid = pgid;
955 sigio->sio_ucred = crhold(curthread->td_ucred);
956 sigio->sio_myref = sigiop;
958 sx_slock(&proctree_lock);
967 * Policy - Don't allow a process to FSETOWN a process
968 * in another session.
970 * Remove this test to allow maximum flexibility or
971 * restrict FSETOWN to the current process or process
972 * group for maximum safety.
975 if (proc->p_session != curthread->td_proc->p_session) {
981 } else /* if (pgid < 0) */ {
982 pgrp = pgfind(-pgid);
990 * Policy - Don't allow a process to FSETOWN a process
991 * in another session.
993 * Remove this test to allow maximum flexibility or
994 * restrict FSETOWN to the current process or process
995 * group for maximum safety.
997 if (pgrp->pg_session != curthread->td_proc->p_session) {
1008 * Since funsetownlst() is called without the proctree
1009 * locked, we need to check for P_WEXIT.
1010 * XXX: is ESRCH correct?
1012 if ((proc->p_flag & P_WEXIT) != 0) {
1017 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1018 sigio->sio_proc = proc;
1022 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1023 sigio->sio_pgrp = pgrp;
1026 sx_sunlock(&proctree_lock);
1033 sx_sunlock(&proctree_lock);
1034 crfree(sigio->sio_ucred);
1035 free(sigio, M_SIGIO);
1040 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1044 struct sigio **sigiop;
1049 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1055 * Close a file descriptor.
1057 #ifndef _SYS_SYSPROTO_H_
1066 struct close_args *uap;
1069 return (kern_close(td, uap->fd));
1077 struct filedesc *fdp;
1084 fdp = td->td_proc->p_fd;
1086 AUDIT_SYSCLOSE(td, fd);
1088 FILEDESC_XLOCK(fdp);
1089 if ((unsigned)fd >= fdp->fd_nfiles ||
1090 (fp = fdp->fd_ofiles[fd]) == NULL) {
1091 FILEDESC_XUNLOCK(fdp);
1094 fdp->fd_ofiles[fd] = NULL;
1095 fdp->fd_ofileflags[fd] = 0;
1097 if (td->td_proc->p_fdtol != NULL) {
1099 * Ask fdfree() to sleep to ensure that all relevant
1100 * process leaders can be traversed in closef().
1102 fdp->fd_holdleaderscount++;
1107 * We now hold the fp reference that used to be owned by the
1108 * descriptor array. We have to unlock the FILEDESC *AFTER*
1109 * knote_fdclose to prevent a race of the fd getting opened, a knote
1110 * added, and deleteing a knote for the new fd.
1112 knote_fdclose(td, fd);
1113 if (fp->f_type == DTYPE_MQUEUE)
1114 mq_fdclose(td, fd, fp);
1115 FILEDESC_XUNLOCK(fdp);
1117 error = closef(fp, td);
1119 FILEDESC_XLOCK(fdp);
1120 fdp->fd_holdleaderscount--;
1121 if (fdp->fd_holdleaderscount == 0 &&
1122 fdp->fd_holdleaderswakeup != 0) {
1123 fdp->fd_holdleaderswakeup = 0;
1124 wakeup(&fdp->fd_holdleaderscount);
1126 FILEDESC_XUNLOCK(fdp);
1132 * Close open file descriptors.
1134 #ifndef _SYS_SYSPROTO_H_
1135 struct closefrom_args {
1141 closefrom(struct thread *td, struct closefrom_args *uap)
1143 struct filedesc *fdp;
1146 fdp = td->td_proc->p_fd;
1147 AUDIT_ARG_FD(uap->lowfd);
1150 * Treat negative starting file descriptor values identical to
1151 * closefrom(0) which closes all files.
1155 FILEDESC_SLOCK(fdp);
1156 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1157 if (fdp->fd_ofiles[fd] != NULL) {
1158 FILEDESC_SUNLOCK(fdp);
1159 (void)kern_close(td, fd);
1160 FILEDESC_SLOCK(fdp);
1163 FILEDESC_SUNLOCK(fdp);
1167 #if defined(COMPAT_43)
1169 * Return status information about a file descriptor.
1171 #ifndef _SYS_SYSPROTO_H_
1172 struct ofstat_args {
1179 ofstat(struct thread *td, struct ofstat_args *uap)
1185 error = kern_fstat(td, uap->fd, &ub);
1188 error = copyout(&oub, uap->sb, sizeof(oub));
1192 #endif /* COMPAT_43 */
1195 * Return status information about a file descriptor.
1197 #ifndef _SYS_SYSPROTO_H_
1205 fstat(struct thread *td, struct fstat_args *uap)
1210 error = kern_fstat(td, uap->fd, &ub);
1212 error = copyout(&ub, uap->sb, sizeof(ub));
1217 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1224 if ((error = fget(td, fd, &fp)) != 0)
1227 AUDIT_ARG_FILE(td->td_proc, fp);
1229 error = fo_stat(fp, sbp, td->td_ucred, td);
1232 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1239 * Return status information about a file descriptor.
1241 #ifndef _SYS_SYSPROTO_H_
1242 struct nfstat_args {
1249 nfstat(struct thread *td, struct nfstat_args *uap)
1255 error = kern_fstat(td, uap->fd, &ub);
1257 cvtnstat(&ub, &nub);
1258 error = copyout(&nub, uap->sb, sizeof(nub));
1264 * Return pathconf information about a file descriptor.
1266 #ifndef _SYS_SYSPROTO_H_
1267 struct fpathconf_args {
1274 fpathconf(struct thread *td, struct fpathconf_args *uap)
1280 if ((error = fget(td, uap->fd, &fp)) != 0)
1283 /* If asynchronous I/O is available, it works for all descriptors. */
1284 if (uap->name == _PC_ASYNC_IO) {
1285 td->td_retval[0] = async_io_version;
1291 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1292 vn_lock(vp, LK_SHARED | LK_RETRY);
1293 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1295 VFS_UNLOCK_GIANT(vfslocked);
1296 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1297 if (uap->name != _PC_PIPE_BUF) {
1300 td->td_retval[0] = PIPE_BUF;
1312 * Grow the file table to accomodate (at least) nfd descriptors. This may
1313 * block and drop the filedesc lock, but it will reacquire it before
1317 fdgrowtable(struct filedesc *fdp, int nfd)
1319 struct filedesc0 *fdp0;
1320 struct freetable *fo;
1321 struct file **ntable;
1322 struct file **otable;
1324 int nnfiles, onfiles;
1327 FILEDESC_XLOCK_ASSERT(fdp);
1329 KASSERT(fdp->fd_nfiles > 0,
1330 ("zero-length file table"));
1332 /* compute the size of the new table */
1333 onfiles = fdp->fd_nfiles;
1334 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1335 if (nnfiles <= onfiles)
1336 /* the table is already large enough */
1339 /* allocate a new table and (if required) new bitmaps */
1340 FILEDESC_XUNLOCK(fdp);
1341 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1342 M_FILEDESC, M_ZERO | M_WAITOK);
1343 nfileflags = (char *)&ntable[nnfiles];
1344 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1345 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1346 M_FILEDESC, M_ZERO | M_WAITOK);
1349 FILEDESC_XLOCK(fdp);
1352 * We now have new tables ready to go. Since we dropped the
1353 * filedesc lock to call malloc(), watch out for a race.
1355 onfiles = fdp->fd_nfiles;
1356 if (onfiles >= nnfiles) {
1357 /* we lost the race, but that's OK */
1358 free(ntable, M_FILEDESC);
1360 free(nmap, M_FILEDESC);
1363 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1364 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1365 otable = fdp->fd_ofiles;
1366 fdp->fd_ofileflags = nfileflags;
1367 fdp->fd_ofiles = ntable;
1369 * We must preserve ofiles until the process exits because we can't
1370 * be certain that no threads have references to the old table via
1373 if (onfiles > NDFILE) {
1374 fo = (struct freetable *)&otable[onfiles];
1375 fdp0 = (struct filedesc0 *)fdp;
1376 fo->ft_table = otable;
1377 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1379 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1380 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1381 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1382 free(fdp->fd_map, M_FILEDESC);
1385 fdp->fd_nfiles = nnfiles;
1389 * Allocate a file descriptor for the process.
1392 fdalloc(struct thread *td, int minfd, int *result)
1394 struct proc *p = td->td_proc;
1395 struct filedesc *fdp = p->p_fd;
1398 FILEDESC_XLOCK_ASSERT(fdp);
1400 if (fdp->fd_freefile > minfd)
1401 minfd = fdp->fd_freefile;
1404 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1408 * Search the bitmap for a free descriptor. If none is found, try
1409 * to grow the file table. Keep at it until we either get a file
1410 * descriptor or run into process or system limits; fdgrowtable()
1411 * may drop the filedesc lock, so we're in a race.
1414 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1417 if (fd < fdp->fd_nfiles)
1419 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1423 * Perform some sanity checks, then mark the file descriptor as
1424 * used and return it to the caller.
1426 KASSERT(!fdisused(fdp, fd),
1427 ("fd_first_free() returned non-free descriptor"));
1428 KASSERT(fdp->fd_ofiles[fd] == NULL,
1429 ("free descriptor isn't"));
1430 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1437 * Check to see whether n user file descriptors are available to the process
1441 fdavail(struct thread *td, int n)
1443 struct proc *p = td->td_proc;
1444 struct filedesc *fdp = td->td_proc->p_fd;
1448 FILEDESC_LOCK_ASSERT(fdp);
1451 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1453 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1455 last = min(fdp->fd_nfiles, lim);
1456 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1457 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1458 if (*fpp == NULL && --n <= 0)
1465 * Create a new open file structure and allocate a file decriptor for the
1466 * process that refers to it. We add one reference to the file for the
1467 * descriptor table and one reference for resultfp. This is to prevent us
1468 * being preempted and the entry in the descriptor table closed after we
1469 * release the FILEDESC lock.
1472 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1474 struct proc *p = td->td_proc;
1477 int maxuserfiles = maxfiles - (maxfiles / 20);
1478 static struct timeval lastfail;
1481 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1482 if ((openfiles >= maxuserfiles &&
1483 priv_check(td, PRIV_MAXFILES) != 0) ||
1484 openfiles >= maxfiles) {
1485 if (ppsratecheck(&lastfail, &curfail, 1)) {
1486 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1487 td->td_ucred->cr_ruid);
1489 uma_zfree(file_zone, fp);
1492 atomic_add_int(&openfiles, 1);
1495 * If the process has file descriptor zero open, add the new file
1496 * descriptor to the list of open files at that point, otherwise
1497 * put it at the front of the list of open files.
1499 refcount_init(&fp->f_count, 1);
1502 fp->f_cred = crhold(td->td_ucred);
1503 fp->f_ops = &badfileops;
1506 FILEDESC_XLOCK(p->p_fd);
1507 if ((error = fdalloc(td, 0, &i))) {
1508 FILEDESC_XUNLOCK(p->p_fd);
1514 p->p_fd->fd_ofiles[i] = fp;
1515 FILEDESC_XUNLOCK(p->p_fd);
1524 * Build a new filedesc structure from another.
1525 * Copy the current, root, and jail root vnode references.
1528 fdinit(struct filedesc *fdp)
1530 struct filedesc0 *newfdp;
1532 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1533 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1535 FILEDESC_XLOCK(fdp);
1536 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1537 if (newfdp->fd_fd.fd_cdir)
1538 VREF(newfdp->fd_fd.fd_cdir);
1539 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1540 if (newfdp->fd_fd.fd_rdir)
1541 VREF(newfdp->fd_fd.fd_rdir);
1542 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1543 if (newfdp->fd_fd.fd_jdir)
1544 VREF(newfdp->fd_fd.fd_jdir);
1545 FILEDESC_XUNLOCK(fdp);
1548 /* Create the file descriptor table. */
1549 newfdp->fd_fd.fd_refcnt = 1;
1550 newfdp->fd_fd.fd_holdcnt = 1;
1551 newfdp->fd_fd.fd_cmask = CMASK;
1552 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1553 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1554 newfdp->fd_fd.fd_nfiles = NDFILE;
1555 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1556 newfdp->fd_fd.fd_lastfile = -1;
1557 return (&newfdp->fd_fd);
1560 static struct filedesc *
1561 fdhold(struct proc *p)
1563 struct filedesc *fdp;
1565 mtx_lock(&fdesc_mtx);
1569 mtx_unlock(&fdesc_mtx);
1574 fddrop(struct filedesc *fdp)
1576 struct filedesc0 *fdp0;
1577 struct freetable *ft;
1580 mtx_lock(&fdesc_mtx);
1581 i = --fdp->fd_holdcnt;
1582 mtx_unlock(&fdesc_mtx);
1586 FILEDESC_LOCK_DESTROY(fdp);
1587 fdp0 = (struct filedesc0 *)fdp;
1588 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1589 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1590 free(ft->ft_table, M_FILEDESC);
1592 free(fdp, M_FILEDESC);
1596 * Share a filedesc structure.
1599 fdshare(struct filedesc *fdp)
1602 FILEDESC_XLOCK(fdp);
1604 FILEDESC_XUNLOCK(fdp);
1609 * Unshare a filedesc structure, if necessary by making a copy
1612 fdunshare(struct proc *p, struct thread *td)
1615 FILEDESC_XLOCK(p->p_fd);
1616 if (p->p_fd->fd_refcnt > 1) {
1617 struct filedesc *tmp;
1619 FILEDESC_XUNLOCK(p->p_fd);
1620 tmp = fdcopy(p->p_fd);
1624 FILEDESC_XUNLOCK(p->p_fd);
1628 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1629 * this is to ease callers, not catch errors.
1632 fdcopy(struct filedesc *fdp)
1634 struct filedesc *newfdp;
1637 /* Certain daemons might not have file descriptors. */
1641 newfdp = fdinit(fdp);
1642 FILEDESC_SLOCK(fdp);
1643 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1644 FILEDESC_SUNLOCK(fdp);
1645 FILEDESC_XLOCK(newfdp);
1646 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1647 FILEDESC_XUNLOCK(newfdp);
1648 FILEDESC_SLOCK(fdp);
1650 /* copy everything except kqueue descriptors */
1651 newfdp->fd_freefile = -1;
1652 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1653 if (fdisused(fdp, i) &&
1654 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1655 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1656 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1657 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1658 fhold(newfdp->fd_ofiles[i]);
1659 newfdp->fd_lastfile = i;
1661 if (newfdp->fd_freefile == -1)
1662 newfdp->fd_freefile = i;
1665 newfdp->fd_cmask = fdp->fd_cmask;
1666 FILEDESC_SUNLOCK(fdp);
1667 FILEDESC_XLOCK(newfdp);
1668 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1669 if (newfdp->fd_ofiles[i] != NULL)
1671 if (newfdp->fd_freefile == -1)
1672 newfdp->fd_freefile = i;
1673 FILEDESC_XUNLOCK(newfdp);
1678 * Release a filedesc structure.
1681 fdfree(struct thread *td)
1683 struct filedesc *fdp;
1686 struct filedesc_to_leader *fdtol;
1688 struct vnode *cdir, *jdir, *rdir, *vp;
1691 /* Certain daemons might not have file descriptors. */
1692 fdp = td->td_proc->p_fd;
1696 /* Check for special need to clear POSIX style locks */
1697 fdtol = td->td_proc->p_fdtol;
1698 if (fdtol != NULL) {
1699 FILEDESC_XLOCK(fdp);
1700 KASSERT(fdtol->fdl_refcount > 0,
1701 ("filedesc_to_refcount botch: fdl_refcount=%d",
1702 fdtol->fdl_refcount));
1703 if (fdtol->fdl_refcount == 1 &&
1704 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1705 for (i = 0, fpp = fdp->fd_ofiles;
1706 i <= fdp->fd_lastfile;
1709 (*fpp)->f_type != DTYPE_VNODE)
1713 FILEDESC_XUNLOCK(fdp);
1714 lf.l_whence = SEEK_SET;
1717 lf.l_type = F_UNLCK;
1719 locked = VFS_LOCK_GIANT(vp->v_mount);
1720 (void) VOP_ADVLOCK(vp,
1721 (caddr_t)td->td_proc->
1726 VFS_UNLOCK_GIANT(locked);
1727 FILEDESC_XLOCK(fdp);
1729 fpp = fdp->fd_ofiles + i;
1733 if (fdtol->fdl_refcount == 1) {
1734 if (fdp->fd_holdleaderscount > 0 &&
1735 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1737 * close() or do_dup() has cleared a reference
1738 * in a shared file descriptor table.
1740 fdp->fd_holdleaderswakeup = 1;
1741 sx_sleep(&fdp->fd_holdleaderscount,
1742 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1745 if (fdtol->fdl_holdcount > 0) {
1747 * Ensure that fdtol->fdl_leader remains
1748 * valid in closef().
1750 fdtol->fdl_wakeup = 1;
1751 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1756 fdtol->fdl_refcount--;
1757 if (fdtol->fdl_refcount == 0 &&
1758 fdtol->fdl_holdcount == 0) {
1759 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1760 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1763 td->td_proc->p_fdtol = NULL;
1764 FILEDESC_XUNLOCK(fdp);
1766 free(fdtol, M_FILEDESC_TO_LEADER);
1768 FILEDESC_XLOCK(fdp);
1769 i = --fdp->fd_refcnt;
1770 FILEDESC_XUNLOCK(fdp);
1774 fpp = fdp->fd_ofiles;
1775 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1777 FILEDESC_XLOCK(fdp);
1780 FILEDESC_XUNLOCK(fdp);
1781 (void) closef(fp, td);
1784 FILEDESC_XLOCK(fdp);
1786 /* XXX This should happen earlier. */
1787 mtx_lock(&fdesc_mtx);
1788 td->td_proc->p_fd = NULL;
1789 mtx_unlock(&fdesc_mtx);
1791 if (fdp->fd_nfiles > NDFILE)
1792 free(fdp->fd_ofiles, M_FILEDESC);
1793 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1794 free(fdp->fd_map, M_FILEDESC);
1798 cdir = fdp->fd_cdir;
1799 fdp->fd_cdir = NULL;
1800 rdir = fdp->fd_rdir;
1801 fdp->fd_rdir = NULL;
1802 jdir = fdp->fd_jdir;
1803 fdp->fd_jdir = NULL;
1804 FILEDESC_XUNLOCK(fdp);
1807 locked = VFS_LOCK_GIANT(cdir->v_mount);
1809 VFS_UNLOCK_GIANT(locked);
1812 locked = VFS_LOCK_GIANT(rdir->v_mount);
1814 VFS_UNLOCK_GIANT(locked);
1817 locked = VFS_LOCK_GIANT(jdir->v_mount);
1819 VFS_UNLOCK_GIANT(locked);
1826 * For setugid programs, we don't want to people to use that setugidness
1827 * to generate error messages which write to a file which otherwise would
1828 * otherwise be off-limits to the process. We check for filesystems where
1829 * the vnode can change out from under us after execve (like [lin]procfs).
1831 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1832 * sufficient. We also don't check for setugidness since we know we are.
1835 is_unsafe(struct file *fp)
1837 if (fp->f_type == DTYPE_VNODE) {
1838 struct vnode *vp = fp->f_vnode;
1840 if ((vp->v_vflag & VV_PROCDEP) != 0)
1847 * Make this setguid thing safe, if at all possible.
1850 setugidsafety(struct thread *td)
1852 struct filedesc *fdp;
1855 /* Certain daemons might not have file descriptors. */
1856 fdp = td->td_proc->p_fd;
1861 * Note: fdp->fd_ofiles may be reallocated out from under us while
1862 * we are blocked in a close. Be careful!
1864 FILEDESC_XLOCK(fdp);
1865 for (i = 0; i <= fdp->fd_lastfile; i++) {
1868 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1871 knote_fdclose(td, i);
1873 * NULL-out descriptor prior to close to avoid
1874 * a race while close blocks.
1876 fp = fdp->fd_ofiles[i];
1877 fdp->fd_ofiles[i] = NULL;
1878 fdp->fd_ofileflags[i] = 0;
1880 FILEDESC_XUNLOCK(fdp);
1881 (void) closef(fp, td);
1882 FILEDESC_XLOCK(fdp);
1885 FILEDESC_XUNLOCK(fdp);
1889 * If a specific file object occupies a specific file descriptor, close the
1890 * file descriptor entry and drop a reference on the file object. This is a
1891 * convenience function to handle a subsequent error in a function that calls
1892 * falloc() that handles the race that another thread might have closed the
1893 * file descriptor out from under the thread creating the file object.
1896 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1899 FILEDESC_XLOCK(fdp);
1900 if (fdp->fd_ofiles[idx] == fp) {
1901 fdp->fd_ofiles[idx] = NULL;
1903 FILEDESC_XUNLOCK(fdp);
1906 FILEDESC_XUNLOCK(fdp);
1910 * Close any files on exec?
1913 fdcloseexec(struct thread *td)
1915 struct filedesc *fdp;
1918 /* Certain daemons might not have file descriptors. */
1919 fdp = td->td_proc->p_fd;
1923 FILEDESC_XLOCK(fdp);
1926 * We cannot cache fd_ofiles or fd_ofileflags since operations
1927 * may block and rip them out from under us.
1929 for (i = 0; i <= fdp->fd_lastfile; i++) {
1930 if (fdp->fd_ofiles[i] != NULL &&
1931 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1932 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1935 knote_fdclose(td, i);
1937 * NULL-out descriptor prior to close to avoid
1938 * a race while close blocks.
1940 fp = fdp->fd_ofiles[i];
1941 fdp->fd_ofiles[i] = NULL;
1942 fdp->fd_ofileflags[i] = 0;
1944 if (fp->f_type == DTYPE_MQUEUE)
1945 mq_fdclose(td, i, fp);
1946 FILEDESC_XUNLOCK(fdp);
1947 (void) closef(fp, td);
1948 FILEDESC_XLOCK(fdp);
1951 FILEDESC_XUNLOCK(fdp);
1955 * It is unsafe for set[ug]id processes to be started with file
1956 * descriptors 0..2 closed, as these descriptors are given implicit
1957 * significance in the Standard C library. fdcheckstd() will create a
1958 * descriptor referencing /dev/null for each of stdin, stdout, and
1959 * stderr that is not already open.
1962 fdcheckstd(struct thread *td)
1964 struct filedesc *fdp;
1965 register_t retval, save;
1966 int i, error, devnull;
1968 fdp = td->td_proc->p_fd;
1971 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1974 for (i = 0; i < 3; i++) {
1975 if (fdp->fd_ofiles[i] != NULL)
1978 save = td->td_retval[0];
1979 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1981 devnull = td->td_retval[0];
1982 KASSERT(devnull == i, ("oof, we didn't get our fd"));
1983 td->td_retval[0] = save;
1987 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1996 * Internal form of close. Decrement reference count on file structure.
1997 * Note: td may be NULL when closing a file that was being passed in a
2000 * XXXRW: Giant is not required for the caller, but often will be held; this
2001 * makes it moderately likely the Giant will be recursed in the VFS case.
2004 closef(struct file *fp, struct thread *td)
2008 struct filedesc_to_leader *fdtol;
2009 struct filedesc *fdp;
2012 * POSIX record locking dictates that any close releases ALL
2013 * locks owned by this process. This is handled by setting
2014 * a flag in the unlock to free ONLY locks obeying POSIX
2015 * semantics, and not to free BSD-style file locks.
2016 * If the descriptor was in a message, POSIX-style locks
2017 * aren't passed with the descriptor, and the thread pointer
2018 * will be NULL. Callers should be careful only to pass a
2019 * NULL thread pointer when there really is no owning
2020 * context that might have locks, or the locks will be
2023 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2027 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2028 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2029 lf.l_whence = SEEK_SET;
2032 lf.l_type = F_UNLCK;
2033 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2034 F_UNLCK, &lf, F_POSIX);
2036 fdtol = td->td_proc->p_fdtol;
2037 if (fdtol != NULL) {
2039 * Handle special case where file descriptor table is
2040 * shared between multiple process leaders.
2042 fdp = td->td_proc->p_fd;
2043 FILEDESC_XLOCK(fdp);
2044 for (fdtol = fdtol->fdl_next;
2045 fdtol != td->td_proc->p_fdtol;
2046 fdtol = fdtol->fdl_next) {
2047 if ((fdtol->fdl_leader->p_flag &
2050 fdtol->fdl_holdcount++;
2051 FILEDESC_XUNLOCK(fdp);
2052 lf.l_whence = SEEK_SET;
2055 lf.l_type = F_UNLCK;
2057 (void) VOP_ADVLOCK(vp,
2058 (caddr_t)fdtol->fdl_leader,
2059 F_UNLCK, &lf, F_POSIX);
2060 FILEDESC_XLOCK(fdp);
2061 fdtol->fdl_holdcount--;
2062 if (fdtol->fdl_holdcount == 0 &&
2063 fdtol->fdl_wakeup != 0) {
2064 fdtol->fdl_wakeup = 0;
2068 FILEDESC_XUNLOCK(fdp);
2070 VFS_UNLOCK_GIANT(vfslocked);
2072 return (fdrop(fp, td));
2076 * Initialize the file pointer with the specified properties.
2078 * The ops are set with release semantics to be certain that the flags, type,
2079 * and data are visible when ops is. This is to prevent ops methods from being
2080 * called with bad data.
2083 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2088 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2092 fget_unlocked(struct filedesc *fdp, int fd)
2097 if (fd < 0 || fd >= fdp->fd_nfiles)
2100 * Fetch the descriptor locklessly. We avoid fdrop() races by
2101 * never raising a refcount above 0. To accomplish this we have
2102 * to use a cmpset loop rather than an atomic_add. The descriptor
2103 * must be re-verified once we acquire a reference to be certain
2104 * that the identity is still correct and we did not lose a race
2105 * due to preemption.
2108 fp = fdp->fd_ofiles[fd];
2111 count = fp->f_count;
2115 * Use an acquire barrier to prevent caching of fd_ofiles
2116 * so it is refreshed for verification.
2118 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2120 if (fp == fdp->fd_ofiles[fd])
2122 fdrop(fp, curthread);
2129 * Extract the file pointer associated with the specified descriptor for the
2130 * current user process.
2132 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2135 * If an error occured the non-zero error is returned and *fpp is set to
2136 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2137 * responsible for fdrop().
2140 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2142 struct filedesc *fdp;
2146 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2148 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2150 if (fp->f_ops == &badfileops) {
2155 * FREAD and FWRITE failure return EBADF as per POSIX.
2157 * Only one flag, or 0, may be specified.
2159 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2160 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2169 fget(struct thread *td, int fd, struct file **fpp)
2172 return(_fget(td, fd, fpp, 0));
2176 fget_read(struct thread *td, int fd, struct file **fpp)
2179 return(_fget(td, fd, fpp, FREAD));
2183 fget_write(struct thread *td, int fd, struct file **fpp)
2186 return(_fget(td, fd, fpp, FWRITE));
2190 * Like fget() but loads the underlying vnode, or returns an error if the
2191 * descriptor does not represent a vnode. Note that pipes use vnodes but
2192 * never have VM objects. The returned vnode will be vref()'d.
2194 * XXX: what about the unused flags ?
2197 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2203 if ((error = _fget(td, fd, &fp, flags)) != 0)
2205 if (fp->f_vnode == NULL) {
2217 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2220 return (_fgetvp(td, fd, vpp, 0));
2224 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2227 return (_fgetvp(td, fd, vpp, FREAD));
2232 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2235 return (_fgetvp(td, fd, vpp, FWRITE));
2240 * Like fget() but loads the underlying socket, or returns an error if the
2241 * descriptor does not represent a socket.
2243 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2246 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2247 * on their file descriptor reference to prevent the socket from being free'd
2251 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2259 if ((error = _fget(td, fd, &fp, 0)) != 0)
2261 if (fp->f_type != DTYPE_SOCKET) {
2266 *fflagp = fp->f_flag;
2277 * Drop the reference count on the socket and XXX release the SX lock in the
2278 * future. The last reference closes the socket.
2280 * Note: fputsock() is deprecated, see comment for fgetsock().
2283 fputsock(struct socket *so)
2292 * Handle the last reference to a file being closed.
2295 _fdrop(struct file *fp, struct thread *td)
2300 if (fp->f_count != 0)
2301 panic("fdrop: count %d", fp->f_count);
2302 if (fp->f_ops != &badfileops)
2303 error = fo_close(fp, td);
2305 * The f_cdevpriv cannot be assigned non-NULL value while we
2306 * are destroying the file.
2308 if (fp->f_cdevpriv != NULL)
2310 atomic_subtract_int(&openfiles, 1);
2312 uma_zfree(file_zone, fp);
2318 * Apply an advisory lock on a file descriptor.
2320 * Just attempt to get a record lock of the requested type on the entire file
2321 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2323 #ifndef _SYS_SYSPROTO_H_
2331 flock(struct thread *td, struct flock_args *uap)
2339 if ((error = fget(td, uap->fd, &fp)) != 0)
2341 if (fp->f_type != DTYPE_VNODE) {
2343 return (EOPNOTSUPP);
2347 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2348 lf.l_whence = SEEK_SET;
2351 if (uap->how & LOCK_UN) {
2352 lf.l_type = F_UNLCK;
2353 atomic_clear_int(&fp->f_flag, FHASLOCK);
2354 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2357 if (uap->how & LOCK_EX)
2358 lf.l_type = F_WRLCK;
2359 else if (uap->how & LOCK_SH)
2360 lf.l_type = F_RDLCK;
2365 atomic_set_int(&fp->f_flag, FHASLOCK);
2366 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2367 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2370 VFS_UNLOCK_GIANT(vfslocked);
2374 * Duplicate the specified descriptor to a free descriptor.
2377 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2383 * If the to-be-dup'd fd number is greater than the allowed number
2384 * of file descriptors, or the fd to be dup'd has already been
2385 * closed, then reject.
2387 FILEDESC_XLOCK(fdp);
2388 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2389 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2390 FILEDESC_XUNLOCK(fdp);
2395 * There are two cases of interest here.
2397 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2399 * For ENXIO steal away the file structure from (dfd) and store it in
2400 * (indx). (dfd) is effectively closed by this operation.
2402 * Any other error code is just returned.
2407 * Check that the mode the file is being opened for is a
2408 * subset of the mode of the existing descriptor.
2410 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2411 FILEDESC_XUNLOCK(fdp);
2414 fp = fdp->fd_ofiles[indx];
2415 fdp->fd_ofiles[indx] = wfp;
2416 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2420 FILEDESC_XUNLOCK(fdp);
2423 * We now own the reference to fp that the ofiles[]
2424 * array used to own. Release it.
2431 * Steal away the file pointer from dfd and stuff it into indx.
2433 fp = fdp->fd_ofiles[indx];
2434 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2435 fdp->fd_ofiles[dfd] = NULL;
2436 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2437 fdp->fd_ofileflags[dfd] = 0;
2441 FILEDESC_XUNLOCK(fdp);
2444 * We now own the reference to fp that the ofiles[] array
2445 * used to own. Release it.
2452 FILEDESC_XUNLOCK(fdp);
2459 * Scan all active processes and prisons to see if any of them have a current
2460 * or root directory of `olddp'. If so, replace them with the new mount point.
2463 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2465 struct filedesc *fdp;
2470 if (vrefcnt(olddp) == 1)
2473 sx_slock(&allproc_lock);
2474 FOREACH_PROC_IN_SYSTEM(p) {
2478 FILEDESC_XLOCK(fdp);
2479 if (fdp->fd_cdir == olddp) {
2481 fdp->fd_cdir = newdp;
2484 if (fdp->fd_rdir == olddp) {
2486 fdp->fd_rdir = newdp;
2489 if (fdp->fd_jdir == olddp) {
2491 fdp->fd_jdir = newdp;
2494 FILEDESC_XUNLOCK(fdp);
2497 sx_sunlock(&allproc_lock);
2498 if (rootvnode == olddp) {
2503 mtx_lock(&prison0.pr_mtx);
2504 if (prison0.pr_root == olddp) {
2506 prison0.pr_root = newdp;
2509 mtx_unlock(&prison0.pr_mtx);
2510 sx_slock(&allprison_lock);
2511 TAILQ_FOREACH(pr, &allprison, pr_list) {
2512 mtx_lock(&pr->pr_mtx);
2513 if (pr->pr_root == olddp) {
2515 pr->pr_root = newdp;
2518 mtx_unlock(&pr->pr_mtx);
2520 sx_sunlock(&allprison_lock);
2525 struct filedesc_to_leader *
2526 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2528 struct filedesc_to_leader *fdtol;
2530 fdtol = malloc(sizeof(struct filedesc_to_leader),
2531 M_FILEDESC_TO_LEADER,
2533 fdtol->fdl_refcount = 1;
2534 fdtol->fdl_holdcount = 0;
2535 fdtol->fdl_wakeup = 0;
2536 fdtol->fdl_leader = leader;
2538 FILEDESC_XLOCK(fdp);
2539 fdtol->fdl_next = old->fdl_next;
2540 fdtol->fdl_prev = old;
2541 old->fdl_next = fdtol;
2542 fdtol->fdl_next->fdl_prev = fdtol;
2543 FILEDESC_XUNLOCK(fdp);
2545 fdtol->fdl_next = fdtol;
2546 fdtol->fdl_prev = fdtol;
2552 * Get file structures globally.
2555 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2558 struct filedesc *fdp;
2563 error = sysctl_wire_old_buffer(req, 0);
2566 if (req->oldptr == NULL) {
2568 sx_slock(&allproc_lock);
2569 FOREACH_PROC_IN_SYSTEM(p) {
2570 if (p->p_state == PRS_NEW)
2575 /* overestimates sparse tables. */
2576 if (fdp->fd_lastfile > 0)
2577 n += fdp->fd_lastfile;
2580 sx_sunlock(&allproc_lock);
2581 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2584 bzero(&xf, sizeof(xf));
2585 xf.xf_size = sizeof(xf);
2586 sx_slock(&allproc_lock);
2587 FOREACH_PROC_IN_SYSTEM(p) {
2588 if (p->p_state == PRS_NEW)
2591 if (p_cansee(req->td, p) != 0) {
2595 xf.xf_pid = p->p_pid;
2596 xf.xf_uid = p->p_ucred->cr_uid;
2601 FILEDESC_SLOCK(fdp);
2602 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2603 if ((fp = fdp->fd_ofiles[n]) == NULL)
2607 xf.xf_data = fp->f_data;
2608 xf.xf_vnode = fp->f_vnode;
2609 xf.xf_type = fp->f_type;
2610 xf.xf_count = fp->f_count;
2612 xf.xf_offset = fp->f_offset;
2613 xf.xf_flag = fp->f_flag;
2614 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2618 FILEDESC_SUNLOCK(fdp);
2623 sx_sunlock(&allproc_lock);
2627 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2628 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2630 #ifdef KINFO_OFILE_SIZE
2631 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2634 #ifdef COMPAT_FREEBSD7
2636 export_vnode_for_osysctl(struct vnode *vp, int type,
2637 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2640 char *fullpath, *freepath;
2643 bzero(kif, sizeof(*kif));
2644 kif->kf_structsize = sizeof(*kif);
2648 kif->kf_type = KF_TYPE_VNODE;
2649 /* This function only handles directories. */
2650 if (vp->v_type != VDIR) {
2654 kif->kf_vnode_type = KF_VTYPE_VDIR;
2657 * This is not a true file descriptor, so we set a bogus refcount
2658 * and offset to indicate these fields should be ignored.
2660 kif->kf_ref_count = -1;
2661 kif->kf_offset = -1;
2665 FILEDESC_SUNLOCK(fdp);
2666 vn_fullpath(curthread, vp, &fullpath, &freepath);
2667 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2669 VFS_UNLOCK_GIANT(vfslocked);
2670 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2671 if (freepath != NULL)
2672 free(freepath, M_TEMP);
2673 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2674 FILEDESC_SLOCK(fdp);
2679 * Get per-process file descriptors for use by procstat(1), et al.
2682 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2684 char *fullpath, *freepath;
2685 struct kinfo_ofile *kif;
2686 struct filedesc *fdp;
2687 int error, i, *name;
2696 if ((p = pfind((pid_t)name[0])) == NULL)
2698 if ((error = p_candebug(curthread, p))) {
2706 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2707 FILEDESC_SLOCK(fdp);
2708 if (fdp->fd_cdir != NULL)
2709 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2711 if (fdp->fd_rdir != NULL)
2712 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2714 if (fdp->fd_jdir != NULL)
2715 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2717 for (i = 0; i < fdp->fd_nfiles; i++) {
2718 if ((fp = fdp->fd_ofiles[i]) == NULL)
2720 bzero(kif, sizeof(*kif));
2721 kif->kf_structsize = sizeof(*kif);
2726 switch (fp->f_type) {
2728 kif->kf_type = KF_TYPE_VNODE;
2733 kif->kf_type = KF_TYPE_SOCKET;
2738 kif->kf_type = KF_TYPE_PIPE;
2742 kif->kf_type = KF_TYPE_FIFO;
2747 kif->kf_type = KF_TYPE_KQUEUE;
2751 kif->kf_type = KF_TYPE_CRYPTO;
2755 kif->kf_type = KF_TYPE_MQUEUE;
2759 kif->kf_type = KF_TYPE_SHM;
2763 kif->kf_type = KF_TYPE_SEM;
2767 kif->kf_type = KF_TYPE_PTS;
2772 kif->kf_type = KF_TYPE_UNKNOWN;
2775 kif->kf_ref_count = fp->f_count;
2776 if (fp->f_flag & FREAD)
2777 kif->kf_flags |= KF_FLAG_READ;
2778 if (fp->f_flag & FWRITE)
2779 kif->kf_flags |= KF_FLAG_WRITE;
2780 if (fp->f_flag & FAPPEND)
2781 kif->kf_flags |= KF_FLAG_APPEND;
2782 if (fp->f_flag & FASYNC)
2783 kif->kf_flags |= KF_FLAG_ASYNC;
2784 if (fp->f_flag & FFSYNC)
2785 kif->kf_flags |= KF_FLAG_FSYNC;
2786 if (fp->f_flag & FNONBLOCK)
2787 kif->kf_flags |= KF_FLAG_NONBLOCK;
2788 if (fp->f_flag & O_DIRECT)
2789 kif->kf_flags |= KF_FLAG_DIRECT;
2790 if (fp->f_flag & FHASLOCK)
2791 kif->kf_flags |= KF_FLAG_HASLOCK;
2792 kif->kf_offset = fp->f_offset;
2795 switch (vp->v_type) {
2797 kif->kf_vnode_type = KF_VTYPE_VNON;
2800 kif->kf_vnode_type = KF_VTYPE_VREG;
2803 kif->kf_vnode_type = KF_VTYPE_VDIR;
2806 kif->kf_vnode_type = KF_VTYPE_VBLK;
2809 kif->kf_vnode_type = KF_VTYPE_VCHR;
2812 kif->kf_vnode_type = KF_VTYPE_VLNK;
2815 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2818 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2821 kif->kf_vnode_type = KF_VTYPE_VBAD;
2824 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2828 * It is OK to drop the filedesc lock here as we will
2829 * re-validate and re-evaluate its properties when
2830 * the loop continues.
2834 FILEDESC_SUNLOCK(fdp);
2835 vn_fullpath(curthread, vp, &fullpath, &freepath);
2836 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2838 VFS_UNLOCK_GIANT(vfslocked);
2839 strlcpy(kif->kf_path, fullpath,
2840 sizeof(kif->kf_path));
2841 if (freepath != NULL)
2842 free(freepath, M_TEMP);
2843 FILEDESC_SLOCK(fdp);
2846 struct sockaddr *sa;
2848 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2849 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2850 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2853 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2854 == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2855 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2858 kif->kf_sock_domain =
2859 so->so_proto->pr_domain->dom_family;
2860 kif->kf_sock_type = so->so_type;
2861 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2864 strlcpy(kif->kf_path, tty_devname(tp),
2865 sizeof(kif->kf_path));
2867 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2871 FILEDESC_SUNLOCK(fdp);
2877 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2878 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2879 #endif /* COMPAT_FREEBSD7 */
2881 #ifdef KINFO_FILE_SIZE
2882 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2886 export_vnode_for_sysctl(struct vnode *vp, int type,
2887 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2890 char *fullpath, *freepath;
2893 bzero(kif, sizeof(*kif));
2897 kif->kf_type = KF_TYPE_VNODE;
2898 /* This function only handles directories. */
2899 if (vp->v_type != VDIR) {
2903 kif->kf_vnode_type = KF_VTYPE_VDIR;
2906 * This is not a true file descriptor, so we set a bogus refcount
2907 * and offset to indicate these fields should be ignored.
2909 kif->kf_ref_count = -1;
2910 kif->kf_offset = -1;
2914 FILEDESC_SUNLOCK(fdp);
2915 vn_fullpath(curthread, vp, &fullpath, &freepath);
2916 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2918 VFS_UNLOCK_GIANT(vfslocked);
2919 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2920 if (freepath != NULL)
2921 free(freepath, M_TEMP);
2922 /* Pack record size down */
2923 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2924 strlen(kif->kf_path) + 1;
2925 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2926 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2927 FILEDESC_SLOCK(fdp);
2932 * Get per-process file descriptors for use by procstat(1), et al.
2935 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2937 char *fullpath, *freepath;
2938 struct kinfo_file *kif;
2939 struct filedesc *fdp;
2940 int error, i, *name;
2950 if ((p = pfind((pid_t)name[0])) == NULL)
2952 if ((error = p_candebug(curthread, p))) {
2960 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2961 FILEDESC_SLOCK(fdp);
2962 if (fdp->fd_cdir != NULL)
2963 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2965 if (fdp->fd_rdir != NULL)
2966 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2968 if (fdp->fd_jdir != NULL)
2969 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2971 for (i = 0; i < fdp->fd_nfiles; i++) {
2972 if ((fp = fdp->fd_ofiles[i]) == NULL)
2974 bzero(kif, sizeof(*kif));
2979 switch (fp->f_type) {
2981 kif->kf_type = KF_TYPE_VNODE;
2986 kif->kf_type = KF_TYPE_SOCKET;
2991 kif->kf_type = KF_TYPE_PIPE;
2995 kif->kf_type = KF_TYPE_FIFO;
3000 kif->kf_type = KF_TYPE_KQUEUE;
3004 kif->kf_type = KF_TYPE_CRYPTO;
3008 kif->kf_type = KF_TYPE_MQUEUE;
3012 kif->kf_type = KF_TYPE_SHM;
3016 kif->kf_type = KF_TYPE_SEM;
3020 kif->kf_type = KF_TYPE_PTS;
3025 kif->kf_type = KF_TYPE_UNKNOWN;
3028 kif->kf_ref_count = fp->f_count;
3029 if (fp->f_flag & FREAD)
3030 kif->kf_flags |= KF_FLAG_READ;
3031 if (fp->f_flag & FWRITE)
3032 kif->kf_flags |= KF_FLAG_WRITE;
3033 if (fp->f_flag & FAPPEND)
3034 kif->kf_flags |= KF_FLAG_APPEND;
3035 if (fp->f_flag & FASYNC)
3036 kif->kf_flags |= KF_FLAG_ASYNC;
3037 if (fp->f_flag & FFSYNC)
3038 kif->kf_flags |= KF_FLAG_FSYNC;
3039 if (fp->f_flag & FNONBLOCK)
3040 kif->kf_flags |= KF_FLAG_NONBLOCK;
3041 if (fp->f_flag & O_DIRECT)
3042 kif->kf_flags |= KF_FLAG_DIRECT;
3043 if (fp->f_flag & FHASLOCK)
3044 kif->kf_flags |= KF_FLAG_HASLOCK;
3045 kif->kf_offset = fp->f_offset;
3048 switch (vp->v_type) {
3050 kif->kf_vnode_type = KF_VTYPE_VNON;
3053 kif->kf_vnode_type = KF_VTYPE_VREG;
3056 kif->kf_vnode_type = KF_VTYPE_VDIR;
3059 kif->kf_vnode_type = KF_VTYPE_VBLK;
3062 kif->kf_vnode_type = KF_VTYPE_VCHR;
3065 kif->kf_vnode_type = KF_VTYPE_VLNK;
3068 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3071 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3074 kif->kf_vnode_type = KF_VTYPE_VBAD;
3077 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3081 * It is OK to drop the filedesc lock here as we will
3082 * re-validate and re-evaluate its properties when
3083 * the loop continues.
3087 FILEDESC_SUNLOCK(fdp);
3088 vn_fullpath(curthread, vp, &fullpath, &freepath);
3089 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3091 VFS_UNLOCK_GIANT(vfslocked);
3092 strlcpy(kif->kf_path, fullpath,
3093 sizeof(kif->kf_path));
3094 if (freepath != NULL)
3095 free(freepath, M_TEMP);
3096 FILEDESC_SLOCK(fdp);
3099 struct sockaddr *sa;
3101 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3102 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3103 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3106 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3107 == 00 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3108 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3111 kif->kf_sock_domain =
3112 so->so_proto->pr_domain->dom_family;
3113 kif->kf_sock_type = so->so_type;
3114 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3117 strlcpy(kif->kf_path, tty_devname(tp),
3118 sizeof(kif->kf_path));
3120 /* Pack record size down */
3121 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3122 strlen(kif->kf_path) + 1;
3123 kif->kf_structsize = roundup(kif->kf_structsize,
3125 oldidx = req->oldidx;
3126 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3128 if (error == ENOMEM) {
3130 * The hack to keep the ABI of sysctl
3131 * kern.proc.filedesc intact, but not
3132 * to account a partially copied
3133 * kinfo_file into the oldidx.
3135 req->oldidx = oldidx;
3141 FILEDESC_SUNLOCK(fdp);
3147 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3148 sysctl_kern_proc_filedesc, "Process filedesc entries");
3152 * For the purposes of debugging, generate a human-readable string for the
3156 file_type_to_name(short type)
3186 * For the purposes of debugging, identify a process (if any, perhaps one of
3187 * many) that references the passed file in its file descriptor array. Return
3190 static struct proc *
3191 file_to_first_proc(struct file *fp)
3193 struct filedesc *fdp;
3197 FOREACH_PROC_IN_SYSTEM(p) {
3198 if (p->p_state == PRS_NEW)
3203 for (n = 0; n < fdp->fd_nfiles; n++) {
3204 if (fp == fdp->fd_ofiles[n])
3212 db_print_file(struct file *fp, int header)
3217 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3218 "File", "Type", "Data", "Flag", "GCFl", "Count",
3219 "MCount", "Vnode", "FPID", "FCmd");
3220 p = file_to_first_proc(fp);
3221 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3222 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3223 0, fp->f_count, 0, fp->f_vnode,
3224 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3227 DB_SHOW_COMMAND(file, db_show_file)
3232 db_printf("usage: show file <addr>\n");
3235 fp = (struct file *)addr;
3236 db_print_file(fp, 1);
3239 DB_SHOW_COMMAND(files, db_show_files)
3241 struct filedesc *fdp;
3248 FOREACH_PROC_IN_SYSTEM(p) {
3249 if (p->p_state == PRS_NEW)
3251 if ((fdp = p->p_fd) == NULL)
3253 for (n = 0; n < fdp->fd_nfiles; ++n) {
3254 if ((fp = fdp->fd_ofiles[n]) == NULL)
3256 db_print_file(fp, header);
3263 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3264 &maxfilesperproc, 0, "Maximum files allowed open per process");
3266 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3267 &maxfiles, 0, "Maximum number of files");
3269 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3270 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3274 filelistinit(void *dummy)
3277 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3278 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3279 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3280 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3282 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3284 /*-------------------------------------------------------------------*/
3287 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3294 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3301 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3308 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3315 badfo_kqfilter(struct file *fp, struct knote *kn)
3322 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3329 badfo_close(struct file *fp, struct thread *td)
3335 struct fileops badfileops = {
3336 .fo_read = badfo_readwrite,
3337 .fo_write = badfo_readwrite,
3338 .fo_truncate = badfo_truncate,
3339 .fo_ioctl = badfo_ioctl,
3340 .fo_poll = badfo_poll,
3341 .fo_kqfilter = badfo_kqfilter,
3342 .fo_stat = badfo_stat,
3343 .fo_close = badfo_close,
3347 /*-------------------------------------------------------------------*/
3350 * File Descriptor pseudo-device driver (/dev/fd/).
3352 * Opening minor device N dup()s the file (if any) connected to file
3353 * descriptor N belonging to the calling process. Note that this driver
3354 * consists of only the ``open()'' routine, because all subsequent
3355 * references to this file will be direct to the other driver.
3357 * XXX: we could give this one a cloning event handler if necessary.
3362 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3366 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3367 * the file descriptor being sought for duplication. The error
3368 * return ensures that the vnode for this device will be released
3369 * by vn_open. Open will detect this special error and take the
3370 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3371 * will simply report the error.
3373 td->td_dupfd = dev2unit(dev);
3377 static struct cdevsw fildesc_cdevsw = {
3378 .d_version = D_VERSION,
3384 fildesc_drvinit(void *unused)
3388 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
3389 make_dev_alias(dev, "stdin");
3390 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
3391 make_dev_alias(dev, "stdout");
3392 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
3393 make_dev_alias(dev, "stderr");
3396 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);