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>
59 #include <sys/mount.h>
60 #include <sys/mqueue.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
65 #include <sys/protosw.h>
66 #include <sys/resourcevar.h>
67 #include <sys/signalvar.h>
68 #include <sys/socketvar.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/sysctl.h>
73 #include <sys/sysproto.h>
75 #include <sys/unistd.h>
77 #include <sys/vnode.h>
79 #include <sys/ktrace.h>
84 #include <security/audit/audit.h>
90 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
91 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
92 "file desc to leader structures");
93 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
95 MALLOC_DECLARE(M_FADVISE);
97 static uma_zone_t file_zone;
100 /* Flags for do_dup() */
101 #define DUP_FIXED 0x1 /* Force fixed allocation */
102 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
103 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
105 static int do_dup(struct thread *td, int flags, int old, int new,
107 static int fd_first_free(struct filedesc *, int, int);
108 static int fd_last_used(struct filedesc *, int, int);
109 static void fdgrowtable(struct filedesc *, int);
110 static void fdunused(struct filedesc *fdp, int fd);
111 static void fdused(struct filedesc *fdp, int fd);
114 * A process is initially started out with NDFILE descriptors stored within
115 * this structure, selected to be enough for typical applications based on
116 * the historical limit of 20 open files (and the usage of descriptors by
117 * shells). If these descriptors are exhausted, a larger descriptor table
118 * may be allocated, up to a process' resource limit; the internal arrays
122 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
123 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
124 #define NDSLOT(x) ((x) / NDENTRIES)
125 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
126 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
129 * Storage required per open file descriptor.
131 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
134 * Storage to hold unused ofiles that need to be reclaimed.
137 struct file **ft_table;
138 SLIST_ENTRY(freetable) ft_next;
142 * Basic allocation of descriptors:
143 * one of the above, plus arrays for NDFILE descriptors.
146 struct filedesc fd_fd;
148 * ofiles which need to be reclaimed on free.
150 SLIST_HEAD(,freetable) fd_free;
152 * These arrays are used when the number of open files is
153 * <= NDFILE, and are then pointed to by the pointers above.
155 struct file *fd_dfiles[NDFILE];
156 char fd_dfileflags[NDFILE];
157 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
161 * Descriptor management.
163 volatile int openfiles; /* actual number of open files */
164 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
165 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
167 /* A mutex to protect the association between a proc and filedesc. */
168 static struct mtx fdesc_mtx;
171 * Find the first zero bit in the given bitmap, starting at low and not
172 * exceeding size - 1.
175 fd_first_free(struct filedesc *fdp, int low, int size)
177 NDSLOTTYPE *map = fdp->fd_map;
185 if (low % NDENTRIES) {
186 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
187 if ((mask &= ~map[off]) != 0UL)
188 return (off * NDENTRIES + ffsl(mask) - 1);
191 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
192 if (map[off] != ~0UL)
193 return (off * NDENTRIES + ffsl(~map[off]) - 1);
198 * Find the highest non-zero bit in the given bitmap, starting at low and
199 * not exceeding size - 1.
202 fd_last_used(struct filedesc *fdp, int low, int size)
204 NDSLOTTYPE *map = fdp->fd_map;
212 if (size % NDENTRIES) {
213 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
214 if ((mask &= map[off]) != 0)
215 return (off * NDENTRIES + flsl(mask) - 1);
218 for (minoff = NDSLOT(low); off >= minoff; --off)
220 return (off * NDENTRIES + flsl(map[off]) - 1);
225 fdisused(struct filedesc *fdp, int fd)
227 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
228 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
229 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
233 * Mark a file descriptor as used.
236 fdused(struct filedesc *fdp, int fd)
239 FILEDESC_XLOCK_ASSERT(fdp);
240 KASSERT(!fdisused(fdp, fd),
241 ("fd already used"));
243 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
244 if (fd > fdp->fd_lastfile)
245 fdp->fd_lastfile = fd;
246 if (fd == fdp->fd_freefile)
247 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
251 * Mark a file descriptor as unused.
254 fdunused(struct filedesc *fdp, int fd)
257 FILEDESC_XLOCK_ASSERT(fdp);
258 KASSERT(fdisused(fdp, fd),
259 ("fd is already unused"));
260 KASSERT(fdp->fd_ofiles[fd] == NULL,
261 ("fd is still in use"));
263 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
264 if (fd < fdp->fd_freefile)
265 fdp->fd_freefile = fd;
266 if (fd == fdp->fd_lastfile)
267 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
271 * System calls on descriptors.
273 #ifndef _SYS_SYSPROTO_H_
274 struct getdtablesize_args {
280 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
282 struct proc *p = td->td_proc;
286 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
292 * Duplicate a file descriptor to a particular value.
294 * Note: keep in mind that a potential race condition exists when closing
295 * descriptors from a shared descriptor table (via rfork).
297 #ifndef _SYS_SYSPROTO_H_
305 dup2(struct thread *td, struct dup2_args *uap)
308 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
313 * Duplicate a file descriptor.
315 #ifndef _SYS_SYSPROTO_H_
322 dup(struct thread *td, struct dup_args *uap)
325 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
329 * The file control system call.
331 #ifndef _SYS_SYSPROTO_H_
340 fcntl(struct thread *td, struct fcntl_args *uap)
355 * Convert old flock structure to new.
357 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
358 fl.l_start = ofl.l_start;
359 fl.l_len = ofl.l_len;
360 fl.l_pid = ofl.l_pid;
361 fl.l_type = ofl.l_type;
362 fl.l_whence = ofl.l_whence;
382 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
391 error = kern_fcntl(td, uap->fd, cmd, arg);
394 if (uap->cmd == F_OGETLK) {
395 ofl.l_start = fl.l_start;
396 ofl.l_len = fl.l_len;
397 ofl.l_pid = fl.l_pid;
398 ofl.l_type = fl.l_type;
399 ofl.l_whence = fl.l_whence;
400 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
401 } else if (uap->cmd == F_GETLK) {
402 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
407 static inline struct file *
408 fdtofp(int fd, struct filedesc *fdp)
412 FILEDESC_LOCK_ASSERT(fdp);
413 if ((unsigned)fd >= fdp->fd_nfiles ||
414 (fp = fdp->fd_ofiles[fd]) == NULL)
420 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
422 struct filedesc *fdp;
442 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
445 case F_DUPFD_CLOEXEC:
447 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
453 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
458 if ((fp = fdtofp(fd, fdp)) == NULL) {
459 FILEDESC_SUNLOCK(fdp);
463 pop = &fdp->fd_ofileflags[fd];
464 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
465 FILEDESC_SUNLOCK(fdp);
470 if ((fp = fdtofp(fd, fdp)) == NULL) {
471 FILEDESC_XUNLOCK(fdp);
475 pop = &fdp->fd_ofileflags[fd];
476 *pop = (*pop &~ UF_EXCLOSE) |
477 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
478 FILEDESC_XUNLOCK(fdp);
483 if ((fp = fdtofp(fd, fdp)) == NULL) {
484 FILEDESC_SUNLOCK(fdp);
488 td->td_retval[0] = OFLAGS(fp->f_flag);
489 FILEDESC_SUNLOCK(fdp);
494 if ((fp = fdtofp(fd, fdp)) == NULL) {
495 FILEDESC_SUNLOCK(fdp);
500 FILEDESC_SUNLOCK(fdp);
502 tmp = flg = fp->f_flag;
504 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
505 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
506 tmp = fp->f_flag & FNONBLOCK;
507 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
512 tmp = fp->f_flag & FASYNC;
513 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
518 atomic_clear_int(&fp->f_flag, FNONBLOCK);
520 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
526 if ((fp = fdtofp(fd, fdp)) == NULL) {
527 FILEDESC_SUNLOCK(fdp);
532 FILEDESC_SUNLOCK(fdp);
533 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
535 td->td_retval[0] = tmp;
541 if ((fp = fdtofp(fd, fdp)) == NULL) {
542 FILEDESC_SUNLOCK(fdp);
547 FILEDESC_SUNLOCK(fdp);
549 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
554 error = priv_check(td, PRIV_NFS_LOCKD);
562 /* FALLTHROUGH F_SETLK */
567 if ((fp = fdtofp(fd, fdp)) == NULL) {
568 FILEDESC_SUNLOCK(fdp);
572 if (fp->f_type != DTYPE_VNODE) {
573 FILEDESC_SUNLOCK(fdp);
577 flp = (struct flock *)arg;
578 if (flp->l_whence == SEEK_CUR) {
579 if (fp->f_offset < 0 ||
581 fp->f_offset > OFF_MAX - flp->l_start)) {
582 FILEDESC_SUNLOCK(fdp);
586 flp->l_start += fp->f_offset;
590 * VOP_ADVLOCK() may block.
593 FILEDESC_SUNLOCK(fdp);
595 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
596 switch (flp->l_type) {
598 if ((fp->f_flag & FREAD) == 0) {
602 PROC_LOCK(p->p_leader);
603 p->p_leader->p_flag |= P_ADVLOCK;
604 PROC_UNLOCK(p->p_leader);
605 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
609 if ((fp->f_flag & FWRITE) == 0) {
613 PROC_LOCK(p->p_leader);
614 p->p_leader->p_flag |= P_ADVLOCK;
615 PROC_UNLOCK(p->p_leader);
616 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
620 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
625 * Temporary api for testing remote lock
628 if (flg != F_REMOTE) {
632 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
633 F_UNLCKSYS, flp, flg);
639 VFS_UNLOCK_GIANT(vfslocked);
641 /* Check for race with close */
643 if ((unsigned) fd >= fdp->fd_nfiles ||
644 fp != fdp->fd_ofiles[fd]) {
645 FILEDESC_SUNLOCK(fdp);
646 flp->l_whence = SEEK_SET;
649 flp->l_type = F_UNLCK;
650 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
651 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
652 F_UNLCK, flp, F_POSIX);
653 VFS_UNLOCK_GIANT(vfslocked);
656 FILEDESC_SUNLOCK(fdp);
662 if ((fp = fdtofp(fd, fdp)) == NULL) {
663 FILEDESC_SUNLOCK(fdp);
667 if (fp->f_type != DTYPE_VNODE) {
668 FILEDESC_SUNLOCK(fdp);
672 flp = (struct flock *)arg;
673 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
674 flp->l_type != F_UNLCK) {
675 FILEDESC_SUNLOCK(fdp);
679 if (flp->l_whence == SEEK_CUR) {
680 if ((flp->l_start > 0 &&
681 fp->f_offset > OFF_MAX - flp->l_start) ||
683 fp->f_offset < OFF_MIN - flp->l_start)) {
684 FILEDESC_SUNLOCK(fdp);
688 flp->l_start += fp->f_offset;
691 * VOP_ADVLOCK() may block.
694 FILEDESC_SUNLOCK(fdp);
696 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
697 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
699 VFS_UNLOCK_GIANT(vfslocked);
705 arg = arg ? 128 * 1024: 0;
709 if ((fp = fdtofp(fd, fdp)) == NULL) {
710 FILEDESC_SUNLOCK(fdp);
714 if (fp->f_type != DTYPE_VNODE) {
715 FILEDESC_SUNLOCK(fdp);
720 FILEDESC_SUNLOCK(fdp);
723 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
724 error = vn_lock(vp, LK_SHARED);
726 goto readahead_vnlock_fail;
727 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
729 fp->f_seqcount = (arg + bsize - 1) / bsize;
731 new = old = fp->f_flag;
733 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
734 readahead_vnlock_fail:
735 VFS_UNLOCK_GIANT(vfslocked);
739 new = old = fp->f_flag;
741 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
750 VFS_UNLOCK_GIANT(vfslocked);
755 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
758 do_dup(struct thread *td, int flags, int old, int new,
761 struct filedesc *fdp;
765 int error, holdleaders, maxfd;
771 * Verify we have a valid descriptor to dup from and possibly to
772 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
773 * return EINVAL when the new descriptor is out of bounds.
778 return (flags & DUP_FCNTL ? EINVAL : EBADF);
780 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
783 return (flags & DUP_FCNTL ? EINVAL : EBADF);
786 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
787 FILEDESC_XUNLOCK(fdp);
790 if (flags & DUP_FIXED && old == new) {
792 FILEDESC_XUNLOCK(fdp);
795 fp = fdp->fd_ofiles[old];
799 * If the caller specified a file descriptor, make sure the file
800 * table is large enough to hold it, and grab it. Otherwise, just
801 * allocate a new descriptor the usual way. Since the filedesc
802 * lock may be temporarily dropped in the process, we have to look
805 if (flags & DUP_FIXED) {
806 if (new >= fdp->fd_nfiles)
807 fdgrowtable(fdp, new + 1);
808 if (fdp->fd_ofiles[new] == NULL)
811 if ((error = fdalloc(td, new, &new)) != 0) {
812 FILEDESC_XUNLOCK(fdp);
819 * If the old file changed out from under us then treat it as a
820 * bad file descriptor. Userland should do its own locking to
823 if (fdp->fd_ofiles[old] != fp) {
824 /* we've allocated a descriptor which we won't use */
825 if (fdp->fd_ofiles[new] == NULL)
827 FILEDESC_XUNLOCK(fdp);
832 ("new fd is same as old"));
835 * Save info on the descriptor being overwritten. We cannot close
836 * it without introducing an ownership race for the slot, since we
837 * need to drop the filedesc lock to call closef().
839 * XXX this duplicates parts of close().
841 delfp = fdp->fd_ofiles[new];
844 if (td->td_proc->p_fdtol != NULL) {
846 * Ask fdfree() to sleep to ensure that all relevant
847 * process leaders can be traversed in closef().
849 fdp->fd_holdleaderscount++;
855 * Duplicate the source descriptor
857 fdp->fd_ofiles[new] = fp;
858 if ((flags & DUP_CLOEXEC) != 0)
859 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
861 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
862 if (new > fdp->fd_lastfile)
863 fdp->fd_lastfile = new;
867 * If we dup'd over a valid file, we now own the reference to it
868 * and must dispose of it using closef() semantics (as if a
869 * close() were performed on it).
871 * XXX this duplicates parts of close().
874 knote_fdclose(td, new);
875 if (delfp->f_type == DTYPE_MQUEUE)
876 mq_fdclose(td, new, delfp);
877 FILEDESC_XUNLOCK(fdp);
878 (void) closef(delfp, td);
881 fdp->fd_holdleaderscount--;
882 if (fdp->fd_holdleaderscount == 0 &&
883 fdp->fd_holdleaderswakeup != 0) {
884 fdp->fd_holdleaderswakeup = 0;
885 wakeup(&fdp->fd_holdleaderscount);
887 FILEDESC_XUNLOCK(fdp);
890 FILEDESC_XUNLOCK(fdp);
896 * If sigio is on the list associated with a process or process group,
897 * disable signalling from the device, remove sigio from the list and
901 funsetown(struct sigio **sigiop)
911 *(sigio->sio_myref) = NULL;
912 if ((sigio)->sio_pgid < 0) {
913 struct pgrp *pg = (sigio)->sio_pgrp;
915 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
919 struct proc *p = (sigio)->sio_proc;
921 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
926 crfree(sigio->sio_ucred);
927 free(sigio, M_SIGIO);
931 * Free a list of sigio structures.
932 * We only need to lock the SIGIO_LOCK because we have made ourselves
933 * inaccessible to callers of fsetown and therefore do not need to lock
934 * the proc or pgrp struct for the list manipulation.
937 funsetownlst(struct sigiolst *sigiolst)
943 sigio = SLIST_FIRST(sigiolst);
950 * Every entry of the list should belong
951 * to a single proc or pgrp.
953 if (sigio->sio_pgid < 0) {
954 pg = sigio->sio_pgrp;
955 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
956 } else /* if (sigio->sio_pgid > 0) */ {
958 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
962 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
963 *(sigio->sio_myref) = NULL;
965 KASSERT(sigio->sio_pgid < 0,
966 ("Proc sigio in pgrp sigio list"));
967 KASSERT(sigio->sio_pgrp == pg,
968 ("Bogus pgrp in sigio list"));
970 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
973 } else /* if (p != NULL) */ {
974 KASSERT(sigio->sio_pgid > 0,
975 ("Pgrp sigio in proc sigio list"));
976 KASSERT(sigio->sio_proc == p,
977 ("Bogus proc in sigio list"));
979 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
984 crfree(sigio->sio_ucred);
985 free(sigio, M_SIGIO);
992 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
994 * After permission checking, add a sigio structure to the sigio list for
995 * the process or process group.
998 fsetown(pid_t pgid, struct sigio **sigiop)
1002 struct sigio *sigio;
1012 /* Allocate and fill in the new sigio out of locks. */
1013 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1014 sigio->sio_pgid = pgid;
1015 sigio->sio_ucred = crhold(curthread->td_ucred);
1016 sigio->sio_myref = sigiop;
1018 sx_slock(&proctree_lock);
1027 * Policy - Don't allow a process to FSETOWN a process
1028 * in another session.
1030 * Remove this test to allow maximum flexibility or
1031 * restrict FSETOWN to the current process or process
1032 * group for maximum safety.
1035 if (proc->p_session != curthread->td_proc->p_session) {
1041 } else /* if (pgid < 0) */ {
1042 pgrp = pgfind(-pgid);
1050 * Policy - Don't allow a process to FSETOWN a process
1051 * in another session.
1053 * Remove this test to allow maximum flexibility or
1054 * restrict FSETOWN to the current process or process
1055 * group for maximum safety.
1057 if (pgrp->pg_session != curthread->td_proc->p_session) {
1068 * Since funsetownlst() is called without the proctree
1069 * locked, we need to check for P_WEXIT.
1070 * XXX: is ESRCH correct?
1072 if ((proc->p_flag & P_WEXIT) != 0) {
1077 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1078 sigio->sio_proc = proc;
1082 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1083 sigio->sio_pgrp = pgrp;
1086 sx_sunlock(&proctree_lock);
1093 sx_sunlock(&proctree_lock);
1094 crfree(sigio->sio_ucred);
1095 free(sigio, M_SIGIO);
1100 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1104 struct sigio **sigiop;
1109 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1115 * Close a file descriptor.
1117 #ifndef _SYS_SYSPROTO_H_
1126 struct close_args *uap;
1129 return (kern_close(td, uap->fd));
1137 struct filedesc *fdp;
1144 fdp = td->td_proc->p_fd;
1146 AUDIT_SYSCLOSE(td, fd);
1148 FILEDESC_XLOCK(fdp);
1149 if ((unsigned)fd >= fdp->fd_nfiles ||
1150 (fp = fdp->fd_ofiles[fd]) == NULL) {
1151 FILEDESC_XUNLOCK(fdp);
1154 fdp->fd_ofiles[fd] = NULL;
1155 fdp->fd_ofileflags[fd] = 0;
1157 if (td->td_proc->p_fdtol != NULL) {
1159 * Ask fdfree() to sleep to ensure that all relevant
1160 * process leaders can be traversed in closef().
1162 fdp->fd_holdleaderscount++;
1167 * We now hold the fp reference that used to be owned by the
1168 * descriptor array. We have to unlock the FILEDESC *AFTER*
1169 * knote_fdclose to prevent a race of the fd getting opened, a knote
1170 * added, and deleteing a knote for the new fd.
1172 knote_fdclose(td, fd);
1173 if (fp->f_type == DTYPE_MQUEUE)
1174 mq_fdclose(td, fd, fp);
1175 FILEDESC_XUNLOCK(fdp);
1177 error = closef(fp, td);
1179 FILEDESC_XLOCK(fdp);
1180 fdp->fd_holdleaderscount--;
1181 if (fdp->fd_holdleaderscount == 0 &&
1182 fdp->fd_holdleaderswakeup != 0) {
1183 fdp->fd_holdleaderswakeup = 0;
1184 wakeup(&fdp->fd_holdleaderscount);
1186 FILEDESC_XUNLOCK(fdp);
1192 * Close open file descriptors.
1194 #ifndef _SYS_SYSPROTO_H_
1195 struct closefrom_args {
1201 closefrom(struct thread *td, struct closefrom_args *uap)
1203 struct filedesc *fdp;
1206 fdp = td->td_proc->p_fd;
1207 AUDIT_ARG_FD(uap->lowfd);
1210 * Treat negative starting file descriptor values identical to
1211 * closefrom(0) which closes all files.
1215 FILEDESC_SLOCK(fdp);
1216 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1217 if (fdp->fd_ofiles[fd] != NULL) {
1218 FILEDESC_SUNLOCK(fdp);
1219 (void)kern_close(td, fd);
1220 FILEDESC_SLOCK(fdp);
1223 FILEDESC_SUNLOCK(fdp);
1227 #if defined(COMPAT_43)
1229 * Return status information about a file descriptor.
1231 #ifndef _SYS_SYSPROTO_H_
1232 struct ofstat_args {
1239 ofstat(struct thread *td, struct ofstat_args *uap)
1245 error = kern_fstat(td, uap->fd, &ub);
1248 error = copyout(&oub, uap->sb, sizeof(oub));
1252 #endif /* COMPAT_43 */
1255 * Return status information about a file descriptor.
1257 #ifndef _SYS_SYSPROTO_H_
1265 fstat(struct thread *td, struct fstat_args *uap)
1270 error = kern_fstat(td, uap->fd, &ub);
1272 error = copyout(&ub, uap->sb, sizeof(ub));
1277 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1284 if ((error = fget(td, fd, &fp)) != 0)
1287 AUDIT_ARG_FILE(td->td_proc, fp);
1289 error = fo_stat(fp, sbp, td->td_ucred, td);
1292 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1299 * Return status information about a file descriptor.
1301 #ifndef _SYS_SYSPROTO_H_
1302 struct nfstat_args {
1309 nfstat(struct thread *td, struct nfstat_args *uap)
1315 error = kern_fstat(td, uap->fd, &ub);
1317 cvtnstat(&ub, &nub);
1318 error = copyout(&nub, uap->sb, sizeof(nub));
1324 * Return pathconf information about a file descriptor.
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct fpathconf_args {
1334 fpathconf(struct thread *td, struct fpathconf_args *uap)
1340 if ((error = fget(td, uap->fd, &fp)) != 0)
1343 /* If asynchronous I/O is available, it works for all descriptors. */
1344 if (uap->name == _PC_ASYNC_IO) {
1345 td->td_retval[0] = async_io_version;
1351 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1352 vn_lock(vp, LK_SHARED | LK_RETRY);
1353 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1355 VFS_UNLOCK_GIANT(vfslocked);
1356 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1357 if (uap->name != _PC_PIPE_BUF) {
1360 td->td_retval[0] = PIPE_BUF;
1372 * Grow the file table to accomodate (at least) nfd descriptors. This may
1373 * block and drop the filedesc lock, but it will reacquire it before
1377 fdgrowtable(struct filedesc *fdp, int nfd)
1379 struct filedesc0 *fdp0;
1380 struct freetable *fo;
1381 struct file **ntable;
1382 struct file **otable;
1384 int nnfiles, onfiles;
1387 FILEDESC_XLOCK_ASSERT(fdp);
1389 KASSERT(fdp->fd_nfiles > 0,
1390 ("zero-length file table"));
1392 /* compute the size of the new table */
1393 onfiles = fdp->fd_nfiles;
1394 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1395 if (nnfiles <= onfiles)
1396 /* the table is already large enough */
1399 /* allocate a new table and (if required) new bitmaps */
1400 FILEDESC_XUNLOCK(fdp);
1401 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1402 M_FILEDESC, M_ZERO | M_WAITOK);
1403 nfileflags = (char *)&ntable[nnfiles];
1404 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1405 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1406 M_FILEDESC, M_ZERO | M_WAITOK);
1409 FILEDESC_XLOCK(fdp);
1412 * We now have new tables ready to go. Since we dropped the
1413 * filedesc lock to call malloc(), watch out for a race.
1415 onfiles = fdp->fd_nfiles;
1416 if (onfiles >= nnfiles) {
1417 /* we lost the race, but that's OK */
1418 free(ntable, M_FILEDESC);
1420 free(nmap, M_FILEDESC);
1423 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1424 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1425 otable = fdp->fd_ofiles;
1426 fdp->fd_ofileflags = nfileflags;
1427 fdp->fd_ofiles = ntable;
1429 * We must preserve ofiles until the process exits because we can't
1430 * be certain that no threads have references to the old table via
1433 if (onfiles > NDFILE) {
1434 fo = (struct freetable *)&otable[onfiles];
1435 fdp0 = (struct filedesc0 *)fdp;
1436 fo->ft_table = otable;
1437 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1439 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1440 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1441 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1442 free(fdp->fd_map, M_FILEDESC);
1445 fdp->fd_nfiles = nnfiles;
1449 * Allocate a file descriptor for the process.
1452 fdalloc(struct thread *td, int minfd, int *result)
1454 struct proc *p = td->td_proc;
1455 struct filedesc *fdp = p->p_fd;
1458 FILEDESC_XLOCK_ASSERT(fdp);
1460 if (fdp->fd_freefile > minfd)
1461 minfd = fdp->fd_freefile;
1464 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1468 * Search the bitmap for a free descriptor. If none is found, try
1469 * to grow the file table. Keep at it until we either get a file
1470 * descriptor or run into process or system limits; fdgrowtable()
1471 * may drop the filedesc lock, so we're in a race.
1474 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1477 if (fd < fdp->fd_nfiles)
1479 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1483 * Perform some sanity checks, then mark the file descriptor as
1484 * used and return it to the caller.
1486 KASSERT(!fdisused(fdp, fd),
1487 ("fd_first_free() returned non-free descriptor"));
1488 KASSERT(fdp->fd_ofiles[fd] == NULL,
1489 ("free descriptor isn't"));
1490 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1497 * Check to see whether n user file descriptors are available to the process
1501 fdavail(struct thread *td, int n)
1503 struct proc *p = td->td_proc;
1504 struct filedesc *fdp = td->td_proc->p_fd;
1508 FILEDESC_LOCK_ASSERT(fdp);
1511 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1513 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1515 last = min(fdp->fd_nfiles, lim);
1516 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1517 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1518 if (*fpp == NULL && --n <= 0)
1525 * Create a new open file structure and allocate a file decriptor for the
1526 * process that refers to it. We add one reference to the file for the
1527 * descriptor table and one reference for resultfp. This is to prevent us
1528 * being preempted and the entry in the descriptor table closed after we
1529 * release the FILEDESC lock.
1532 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1534 struct proc *p = td->td_proc;
1537 int maxuserfiles = maxfiles - (maxfiles / 20);
1538 static struct timeval lastfail;
1541 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1542 if ((openfiles >= maxuserfiles &&
1543 priv_check(td, PRIV_MAXFILES) != 0) ||
1544 openfiles >= maxfiles) {
1545 if (ppsratecheck(&lastfail, &curfail, 1)) {
1546 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1547 td->td_ucred->cr_ruid);
1549 uma_zfree(file_zone, fp);
1552 atomic_add_int(&openfiles, 1);
1555 * If the process has file descriptor zero open, add the new file
1556 * descriptor to the list of open files at that point, otherwise
1557 * put it at the front of the list of open files.
1559 refcount_init(&fp->f_count, 1);
1562 fp->f_cred = crhold(td->td_ucred);
1563 fp->f_ops = &badfileops;
1566 FILEDESC_XLOCK(p->p_fd);
1567 if ((error = fdalloc(td, 0, &i))) {
1568 FILEDESC_XUNLOCK(p->p_fd);
1574 p->p_fd->fd_ofiles[i] = fp;
1575 if ((flags & O_CLOEXEC) != 0)
1576 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1577 FILEDESC_XUNLOCK(p->p_fd);
1586 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1589 return (fallocf(td, resultfp, resultfd, 0));
1593 * Build a new filedesc structure from another.
1594 * Copy the current, root, and jail root vnode references.
1597 fdinit(struct filedesc *fdp)
1599 struct filedesc0 *newfdp;
1601 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1602 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1604 FILEDESC_XLOCK(fdp);
1605 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1606 if (newfdp->fd_fd.fd_cdir)
1607 VREF(newfdp->fd_fd.fd_cdir);
1608 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1609 if (newfdp->fd_fd.fd_rdir)
1610 VREF(newfdp->fd_fd.fd_rdir);
1611 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1612 if (newfdp->fd_fd.fd_jdir)
1613 VREF(newfdp->fd_fd.fd_jdir);
1614 FILEDESC_XUNLOCK(fdp);
1617 /* Create the file descriptor table. */
1618 newfdp->fd_fd.fd_refcnt = 1;
1619 newfdp->fd_fd.fd_holdcnt = 1;
1620 newfdp->fd_fd.fd_cmask = CMASK;
1621 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1622 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1623 newfdp->fd_fd.fd_nfiles = NDFILE;
1624 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1625 newfdp->fd_fd.fd_lastfile = -1;
1626 return (&newfdp->fd_fd);
1629 static struct filedesc *
1630 fdhold(struct proc *p)
1632 struct filedesc *fdp;
1634 mtx_lock(&fdesc_mtx);
1638 mtx_unlock(&fdesc_mtx);
1643 fddrop(struct filedesc *fdp)
1645 struct filedesc0 *fdp0;
1646 struct freetable *ft;
1649 mtx_lock(&fdesc_mtx);
1650 i = --fdp->fd_holdcnt;
1651 mtx_unlock(&fdesc_mtx);
1655 FILEDESC_LOCK_DESTROY(fdp);
1656 fdp0 = (struct filedesc0 *)fdp;
1657 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1658 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1659 free(ft->ft_table, M_FILEDESC);
1661 free(fdp, M_FILEDESC);
1665 * Share a filedesc structure.
1668 fdshare(struct filedesc *fdp)
1671 FILEDESC_XLOCK(fdp);
1673 FILEDESC_XUNLOCK(fdp);
1678 * Unshare a filedesc structure, if necessary by making a copy
1681 fdunshare(struct proc *p, struct thread *td)
1684 FILEDESC_XLOCK(p->p_fd);
1685 if (p->p_fd->fd_refcnt > 1) {
1686 struct filedesc *tmp;
1688 FILEDESC_XUNLOCK(p->p_fd);
1689 tmp = fdcopy(p->p_fd);
1693 FILEDESC_XUNLOCK(p->p_fd);
1697 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1698 * this is to ease callers, not catch errors.
1701 fdcopy(struct filedesc *fdp)
1703 struct filedesc *newfdp;
1706 /* Certain daemons might not have file descriptors. */
1710 newfdp = fdinit(fdp);
1711 FILEDESC_SLOCK(fdp);
1712 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1713 FILEDESC_SUNLOCK(fdp);
1714 FILEDESC_XLOCK(newfdp);
1715 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1716 FILEDESC_XUNLOCK(newfdp);
1717 FILEDESC_SLOCK(fdp);
1719 /* copy everything except kqueue descriptors */
1720 newfdp->fd_freefile = -1;
1721 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1722 if (fdisused(fdp, i) &&
1723 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1724 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1725 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1726 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1727 fhold(newfdp->fd_ofiles[i]);
1728 newfdp->fd_lastfile = i;
1730 if (newfdp->fd_freefile == -1)
1731 newfdp->fd_freefile = i;
1734 newfdp->fd_cmask = fdp->fd_cmask;
1735 FILEDESC_SUNLOCK(fdp);
1736 FILEDESC_XLOCK(newfdp);
1737 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1738 if (newfdp->fd_ofiles[i] != NULL)
1740 if (newfdp->fd_freefile == -1)
1741 newfdp->fd_freefile = i;
1742 FILEDESC_XUNLOCK(newfdp);
1747 * Release a filedesc structure.
1750 fdfree(struct thread *td)
1752 struct filedesc *fdp;
1755 struct filedesc_to_leader *fdtol;
1757 struct vnode *cdir, *jdir, *rdir, *vp;
1760 /* Certain daemons might not have file descriptors. */
1761 fdp = td->td_proc->p_fd;
1765 /* Check for special need to clear POSIX style locks */
1766 fdtol = td->td_proc->p_fdtol;
1767 if (fdtol != NULL) {
1768 FILEDESC_XLOCK(fdp);
1769 KASSERT(fdtol->fdl_refcount > 0,
1770 ("filedesc_to_refcount botch: fdl_refcount=%d",
1771 fdtol->fdl_refcount));
1772 if (fdtol->fdl_refcount == 1 &&
1773 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1774 for (i = 0, fpp = fdp->fd_ofiles;
1775 i <= fdp->fd_lastfile;
1778 (*fpp)->f_type != DTYPE_VNODE)
1782 FILEDESC_XUNLOCK(fdp);
1783 lf.l_whence = SEEK_SET;
1786 lf.l_type = F_UNLCK;
1788 locked = VFS_LOCK_GIANT(vp->v_mount);
1789 (void) VOP_ADVLOCK(vp,
1790 (caddr_t)td->td_proc->
1795 VFS_UNLOCK_GIANT(locked);
1796 FILEDESC_XLOCK(fdp);
1798 fpp = fdp->fd_ofiles + i;
1802 if (fdtol->fdl_refcount == 1) {
1803 if (fdp->fd_holdleaderscount > 0 &&
1804 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1806 * close() or do_dup() has cleared a reference
1807 * in a shared file descriptor table.
1809 fdp->fd_holdleaderswakeup = 1;
1810 sx_sleep(&fdp->fd_holdleaderscount,
1811 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1814 if (fdtol->fdl_holdcount > 0) {
1816 * Ensure that fdtol->fdl_leader remains
1817 * valid in closef().
1819 fdtol->fdl_wakeup = 1;
1820 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1825 fdtol->fdl_refcount--;
1826 if (fdtol->fdl_refcount == 0 &&
1827 fdtol->fdl_holdcount == 0) {
1828 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1829 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1832 td->td_proc->p_fdtol = NULL;
1833 FILEDESC_XUNLOCK(fdp);
1835 free(fdtol, M_FILEDESC_TO_LEADER);
1837 FILEDESC_XLOCK(fdp);
1838 i = --fdp->fd_refcnt;
1839 FILEDESC_XUNLOCK(fdp);
1843 fpp = fdp->fd_ofiles;
1844 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1846 FILEDESC_XLOCK(fdp);
1849 FILEDESC_XUNLOCK(fdp);
1850 (void) closef(fp, td);
1853 FILEDESC_XLOCK(fdp);
1855 /* XXX This should happen earlier. */
1856 mtx_lock(&fdesc_mtx);
1857 td->td_proc->p_fd = NULL;
1858 mtx_unlock(&fdesc_mtx);
1860 if (fdp->fd_nfiles > NDFILE)
1861 free(fdp->fd_ofiles, M_FILEDESC);
1862 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1863 free(fdp->fd_map, M_FILEDESC);
1867 cdir = fdp->fd_cdir;
1868 fdp->fd_cdir = NULL;
1869 rdir = fdp->fd_rdir;
1870 fdp->fd_rdir = NULL;
1871 jdir = fdp->fd_jdir;
1872 fdp->fd_jdir = NULL;
1873 FILEDESC_XUNLOCK(fdp);
1876 locked = VFS_LOCK_GIANT(cdir->v_mount);
1878 VFS_UNLOCK_GIANT(locked);
1881 locked = VFS_LOCK_GIANT(rdir->v_mount);
1883 VFS_UNLOCK_GIANT(locked);
1886 locked = VFS_LOCK_GIANT(jdir->v_mount);
1888 VFS_UNLOCK_GIANT(locked);
1895 * For setugid programs, we don't want to people to use that setugidness
1896 * to generate error messages which write to a file which otherwise would
1897 * otherwise be off-limits to the process. We check for filesystems where
1898 * the vnode can change out from under us after execve (like [lin]procfs).
1900 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1901 * sufficient. We also don't check for setugidness since we know we are.
1904 is_unsafe(struct file *fp)
1906 if (fp->f_type == DTYPE_VNODE) {
1907 struct vnode *vp = fp->f_vnode;
1909 if ((vp->v_vflag & VV_PROCDEP) != 0)
1916 * Make this setguid thing safe, if at all possible.
1919 setugidsafety(struct thread *td)
1921 struct filedesc *fdp;
1924 /* Certain daemons might not have file descriptors. */
1925 fdp = td->td_proc->p_fd;
1930 * Note: fdp->fd_ofiles may be reallocated out from under us while
1931 * we are blocked in a close. Be careful!
1933 FILEDESC_XLOCK(fdp);
1934 for (i = 0; i <= fdp->fd_lastfile; i++) {
1937 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1940 knote_fdclose(td, i);
1942 * NULL-out descriptor prior to close to avoid
1943 * a race while close blocks.
1945 fp = fdp->fd_ofiles[i];
1946 fdp->fd_ofiles[i] = NULL;
1947 fdp->fd_ofileflags[i] = 0;
1949 FILEDESC_XUNLOCK(fdp);
1950 (void) closef(fp, td);
1951 FILEDESC_XLOCK(fdp);
1954 FILEDESC_XUNLOCK(fdp);
1958 * If a specific file object occupies a specific file descriptor, close the
1959 * file descriptor entry and drop a reference on the file object. This is a
1960 * convenience function to handle a subsequent error in a function that calls
1961 * falloc() that handles the race that another thread might have closed the
1962 * file descriptor out from under the thread creating the file object.
1965 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1968 FILEDESC_XLOCK(fdp);
1969 if (fdp->fd_ofiles[idx] == fp) {
1970 fdp->fd_ofiles[idx] = NULL;
1972 FILEDESC_XUNLOCK(fdp);
1975 FILEDESC_XUNLOCK(fdp);
1979 * Close any files on exec?
1982 fdcloseexec(struct thread *td)
1984 struct filedesc *fdp;
1987 /* Certain daemons might not have file descriptors. */
1988 fdp = td->td_proc->p_fd;
1992 FILEDESC_XLOCK(fdp);
1995 * We cannot cache fd_ofiles or fd_ofileflags since operations
1996 * may block and rip them out from under us.
1998 for (i = 0; i <= fdp->fd_lastfile; i++) {
1999 if (fdp->fd_ofiles[i] != NULL &&
2000 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2001 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2004 knote_fdclose(td, i);
2006 * NULL-out descriptor prior to close to avoid
2007 * a race while close blocks.
2009 fp = fdp->fd_ofiles[i];
2010 fdp->fd_ofiles[i] = NULL;
2011 fdp->fd_ofileflags[i] = 0;
2013 if (fp->f_type == DTYPE_MQUEUE)
2014 mq_fdclose(td, i, fp);
2015 FILEDESC_XUNLOCK(fdp);
2016 (void) closef(fp, td);
2017 FILEDESC_XLOCK(fdp);
2020 FILEDESC_XUNLOCK(fdp);
2024 * It is unsafe for set[ug]id processes to be started with file
2025 * descriptors 0..2 closed, as these descriptors are given implicit
2026 * significance in the Standard C library. fdcheckstd() will create a
2027 * descriptor referencing /dev/null for each of stdin, stdout, and
2028 * stderr that is not already open.
2031 fdcheckstd(struct thread *td)
2033 struct filedesc *fdp;
2034 register_t retval, save;
2035 int i, error, devnull;
2037 fdp = td->td_proc->p_fd;
2040 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2043 for (i = 0; i < 3; i++) {
2044 if (fdp->fd_ofiles[i] != NULL)
2047 save = td->td_retval[0];
2048 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2050 devnull = td->td_retval[0];
2051 td->td_retval[0] = save;
2054 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2056 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2065 * Internal form of close. Decrement reference count on file structure.
2066 * Note: td may be NULL when closing a file that was being passed in a
2069 * XXXRW: Giant is not required for the caller, but often will be held; this
2070 * makes it moderately likely the Giant will be recursed in the VFS case.
2073 closef(struct file *fp, struct thread *td)
2077 struct filedesc_to_leader *fdtol;
2078 struct filedesc *fdp;
2081 * POSIX record locking dictates that any close releases ALL
2082 * locks owned by this process. This is handled by setting
2083 * a flag in the unlock to free ONLY locks obeying POSIX
2084 * semantics, and not to free BSD-style file locks.
2085 * If the descriptor was in a message, POSIX-style locks
2086 * aren't passed with the descriptor, and the thread pointer
2087 * will be NULL. Callers should be careful only to pass a
2088 * NULL thread pointer when there really is no owning
2089 * context that might have locks, or the locks will be
2092 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2096 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2097 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2098 lf.l_whence = SEEK_SET;
2101 lf.l_type = F_UNLCK;
2102 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2103 F_UNLCK, &lf, F_POSIX);
2105 fdtol = td->td_proc->p_fdtol;
2106 if (fdtol != NULL) {
2108 * Handle special case where file descriptor table is
2109 * shared between multiple process leaders.
2111 fdp = td->td_proc->p_fd;
2112 FILEDESC_XLOCK(fdp);
2113 for (fdtol = fdtol->fdl_next;
2114 fdtol != td->td_proc->p_fdtol;
2115 fdtol = fdtol->fdl_next) {
2116 if ((fdtol->fdl_leader->p_flag &
2119 fdtol->fdl_holdcount++;
2120 FILEDESC_XUNLOCK(fdp);
2121 lf.l_whence = SEEK_SET;
2124 lf.l_type = F_UNLCK;
2126 (void) VOP_ADVLOCK(vp,
2127 (caddr_t)fdtol->fdl_leader,
2128 F_UNLCK, &lf, F_POSIX);
2129 FILEDESC_XLOCK(fdp);
2130 fdtol->fdl_holdcount--;
2131 if (fdtol->fdl_holdcount == 0 &&
2132 fdtol->fdl_wakeup != 0) {
2133 fdtol->fdl_wakeup = 0;
2137 FILEDESC_XUNLOCK(fdp);
2139 VFS_UNLOCK_GIANT(vfslocked);
2141 return (fdrop(fp, td));
2145 * Initialize the file pointer with the specified properties.
2147 * The ops are set with release semantics to be certain that the flags, type,
2148 * and data are visible when ops is. This is to prevent ops methods from being
2149 * called with bad data.
2152 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2157 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2161 fget_unlocked(struct filedesc *fdp, int fd)
2166 if (fd < 0 || fd >= fdp->fd_nfiles)
2169 * Fetch the descriptor locklessly. We avoid fdrop() races by
2170 * never raising a refcount above 0. To accomplish this we have
2171 * to use a cmpset loop rather than an atomic_add. The descriptor
2172 * must be re-verified once we acquire a reference to be certain
2173 * that the identity is still correct and we did not lose a race
2174 * due to preemption.
2177 fp = fdp->fd_ofiles[fd];
2180 count = fp->f_count;
2184 * Use an acquire barrier to prevent caching of fd_ofiles
2185 * so it is refreshed for verification.
2187 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2189 if (fp == fdp->fd_ofiles[fd])
2191 fdrop(fp, curthread);
2198 * Extract the file pointer associated with the specified descriptor for the
2199 * current user process.
2201 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2204 * If an error occured the non-zero error is returned and *fpp is set to
2205 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2206 * responsible for fdrop().
2209 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2211 struct filedesc *fdp;
2215 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2217 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2219 if (fp->f_ops == &badfileops) {
2224 * FREAD and FWRITE failure return EBADF as per POSIX.
2226 * Only one flag, or 0, may be specified.
2228 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2229 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2238 fget(struct thread *td, int fd, struct file **fpp)
2241 return(_fget(td, fd, fpp, 0));
2245 fget_read(struct thread *td, int fd, struct file **fpp)
2248 return(_fget(td, fd, fpp, FREAD));
2252 fget_write(struct thread *td, int fd, struct file **fpp)
2255 return(_fget(td, fd, fpp, FWRITE));
2259 * Like fget() but loads the underlying vnode, or returns an error if the
2260 * descriptor does not represent a vnode. Note that pipes use vnodes but
2261 * never have VM objects. The returned vnode will be vref()'d.
2263 * XXX: what about the unused flags ?
2266 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2272 if ((error = _fget(td, fd, &fp, flags)) != 0)
2274 if (fp->f_vnode == NULL) {
2286 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2289 return (_fgetvp(td, fd, vpp, 0));
2293 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2296 return (_fgetvp(td, fd, vpp, FREAD));
2301 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2304 return (_fgetvp(td, fd, vpp, FWRITE));
2309 * Like fget() but loads the underlying socket, or returns an error if the
2310 * descriptor does not represent a socket.
2312 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2315 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2316 * on their file descriptor reference to prevent the socket from being free'd
2320 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2328 if ((error = _fget(td, fd, &fp, 0)) != 0)
2330 if (fp->f_type != DTYPE_SOCKET) {
2335 *fflagp = fp->f_flag;
2346 * Drop the reference count on the socket and XXX release the SX lock in the
2347 * future. The last reference closes the socket.
2349 * Note: fputsock() is deprecated, see comment for fgetsock().
2352 fputsock(struct socket *so)
2357 CURVNET_SET(so->so_vnet);
2363 * Handle the last reference to a file being closed.
2366 _fdrop(struct file *fp, struct thread *td)
2371 if (fp->f_count != 0)
2372 panic("fdrop: count %d", fp->f_count);
2373 if (fp->f_ops != &badfileops)
2374 error = fo_close(fp, td);
2375 atomic_subtract_int(&openfiles, 1);
2377 free(fp->f_advice, M_FADVISE);
2378 uma_zfree(file_zone, fp);
2384 * Apply an advisory lock on a file descriptor.
2386 * Just attempt to get a record lock of the requested type on the entire file
2387 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2389 #ifndef _SYS_SYSPROTO_H_
2397 flock(struct thread *td, struct flock_args *uap)
2405 if ((error = fget(td, uap->fd, &fp)) != 0)
2407 if (fp->f_type != DTYPE_VNODE) {
2409 return (EOPNOTSUPP);
2413 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2414 lf.l_whence = SEEK_SET;
2417 if (uap->how & LOCK_UN) {
2418 lf.l_type = F_UNLCK;
2419 atomic_clear_int(&fp->f_flag, FHASLOCK);
2420 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2423 if (uap->how & LOCK_EX)
2424 lf.l_type = F_WRLCK;
2425 else if (uap->how & LOCK_SH)
2426 lf.l_type = F_RDLCK;
2431 atomic_set_int(&fp->f_flag, FHASLOCK);
2432 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2433 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2436 VFS_UNLOCK_GIANT(vfslocked);
2440 * Duplicate the specified descriptor to a free descriptor.
2443 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2449 * If the to-be-dup'd fd number is greater than the allowed number
2450 * of file descriptors, or the fd to be dup'd has already been
2451 * closed, then reject.
2453 FILEDESC_XLOCK(fdp);
2454 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2455 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2456 FILEDESC_XUNLOCK(fdp);
2461 * There are two cases of interest here.
2463 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2465 * For ENXIO steal away the file structure from (dfd) and store it in
2466 * (indx). (dfd) is effectively closed by this operation.
2468 * Any other error code is just returned.
2473 * Check that the mode the file is being opened for is a
2474 * subset of the mode of the existing descriptor.
2476 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2477 FILEDESC_XUNLOCK(fdp);
2480 fp = fdp->fd_ofiles[indx];
2481 fdp->fd_ofiles[indx] = wfp;
2482 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2486 FILEDESC_XUNLOCK(fdp);
2489 * We now own the reference to fp that the ofiles[]
2490 * array used to own. Release it.
2497 * Steal away the file pointer from dfd and stuff it into indx.
2499 fp = fdp->fd_ofiles[indx];
2500 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2501 fdp->fd_ofiles[dfd] = NULL;
2502 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2503 fdp->fd_ofileflags[dfd] = 0;
2507 FILEDESC_XUNLOCK(fdp);
2510 * We now own the reference to fp that the ofiles[] array
2511 * used to own. Release it.
2518 FILEDESC_XUNLOCK(fdp);
2525 * Scan all active processes and prisons to see if any of them have a current
2526 * or root directory of `olddp'. If so, replace them with the new mount point.
2529 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2531 struct filedesc *fdp;
2536 if (vrefcnt(olddp) == 1)
2539 sx_slock(&allproc_lock);
2540 FOREACH_PROC_IN_SYSTEM(p) {
2544 FILEDESC_XLOCK(fdp);
2545 if (fdp->fd_cdir == olddp) {
2547 fdp->fd_cdir = newdp;
2550 if (fdp->fd_rdir == olddp) {
2552 fdp->fd_rdir = newdp;
2555 if (fdp->fd_jdir == olddp) {
2557 fdp->fd_jdir = newdp;
2560 FILEDESC_XUNLOCK(fdp);
2563 sx_sunlock(&allproc_lock);
2564 if (rootvnode == olddp) {
2569 mtx_lock(&prison0.pr_mtx);
2570 if (prison0.pr_root == olddp) {
2572 prison0.pr_root = newdp;
2575 mtx_unlock(&prison0.pr_mtx);
2576 sx_slock(&allprison_lock);
2577 TAILQ_FOREACH(pr, &allprison, pr_list) {
2578 mtx_lock(&pr->pr_mtx);
2579 if (pr->pr_root == olddp) {
2581 pr->pr_root = newdp;
2584 mtx_unlock(&pr->pr_mtx);
2586 sx_sunlock(&allprison_lock);
2591 struct filedesc_to_leader *
2592 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2594 struct filedesc_to_leader *fdtol;
2596 fdtol = malloc(sizeof(struct filedesc_to_leader),
2597 M_FILEDESC_TO_LEADER,
2599 fdtol->fdl_refcount = 1;
2600 fdtol->fdl_holdcount = 0;
2601 fdtol->fdl_wakeup = 0;
2602 fdtol->fdl_leader = leader;
2604 FILEDESC_XLOCK(fdp);
2605 fdtol->fdl_next = old->fdl_next;
2606 fdtol->fdl_prev = old;
2607 old->fdl_next = fdtol;
2608 fdtol->fdl_next->fdl_prev = fdtol;
2609 FILEDESC_XUNLOCK(fdp);
2611 fdtol->fdl_next = fdtol;
2612 fdtol->fdl_prev = fdtol;
2618 * Get file structures globally.
2621 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2624 struct filedesc *fdp;
2629 error = sysctl_wire_old_buffer(req, 0);
2632 if (req->oldptr == NULL) {
2634 sx_slock(&allproc_lock);
2635 FOREACH_PROC_IN_SYSTEM(p) {
2636 if (p->p_state == PRS_NEW)
2641 /* overestimates sparse tables. */
2642 if (fdp->fd_lastfile > 0)
2643 n += fdp->fd_lastfile;
2646 sx_sunlock(&allproc_lock);
2647 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2650 bzero(&xf, sizeof(xf));
2651 xf.xf_size = sizeof(xf);
2652 sx_slock(&allproc_lock);
2653 FOREACH_PROC_IN_SYSTEM(p) {
2655 if (p->p_state == PRS_NEW) {
2659 if (p_cansee(req->td, p) != 0) {
2663 xf.xf_pid = p->p_pid;
2664 xf.xf_uid = p->p_ucred->cr_uid;
2669 FILEDESC_SLOCK(fdp);
2670 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2671 if ((fp = fdp->fd_ofiles[n]) == NULL)
2675 xf.xf_data = fp->f_data;
2676 xf.xf_vnode = fp->f_vnode;
2677 xf.xf_type = fp->f_type;
2678 xf.xf_count = fp->f_count;
2680 xf.xf_offset = fp->f_offset;
2681 xf.xf_flag = fp->f_flag;
2682 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2686 FILEDESC_SUNLOCK(fdp);
2691 sx_sunlock(&allproc_lock);
2695 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2696 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2698 #ifdef KINFO_OFILE_SIZE
2699 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2702 #ifdef COMPAT_FREEBSD7
2704 export_vnode_for_osysctl(struct vnode *vp, int type,
2705 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2708 char *fullpath, *freepath;
2711 bzero(kif, sizeof(*kif));
2712 kif->kf_structsize = sizeof(*kif);
2716 kif->kf_type = KF_TYPE_VNODE;
2717 /* This function only handles directories. */
2718 if (vp->v_type != VDIR) {
2722 kif->kf_vnode_type = KF_VTYPE_VDIR;
2725 * This is not a true file descriptor, so we set a bogus refcount
2726 * and offset to indicate these fields should be ignored.
2728 kif->kf_ref_count = -1;
2729 kif->kf_offset = -1;
2733 FILEDESC_SUNLOCK(fdp);
2734 vn_fullpath(curthread, vp, &fullpath, &freepath);
2735 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2737 VFS_UNLOCK_GIANT(vfslocked);
2738 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2739 if (freepath != NULL)
2740 free(freepath, M_TEMP);
2741 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2742 FILEDESC_SLOCK(fdp);
2747 * Get per-process file descriptors for use by procstat(1), et al.
2750 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2752 char *fullpath, *freepath;
2753 struct kinfo_ofile *kif;
2754 struct filedesc *fdp;
2755 int error, i, *name;
2756 struct shmfd *shmfd;
2765 if ((p = pfind((pid_t)name[0])) == NULL)
2767 if ((error = p_candebug(curthread, p))) {
2775 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2776 FILEDESC_SLOCK(fdp);
2777 if (fdp->fd_cdir != NULL)
2778 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2780 if (fdp->fd_rdir != NULL)
2781 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2783 if (fdp->fd_jdir != NULL)
2784 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2786 for (i = 0; i < fdp->fd_nfiles; i++) {
2787 if ((fp = fdp->fd_ofiles[i]) == NULL)
2789 bzero(kif, sizeof(*kif));
2790 kif->kf_structsize = sizeof(*kif);
2796 switch (fp->f_type) {
2798 kif->kf_type = KF_TYPE_VNODE;
2803 kif->kf_type = KF_TYPE_SOCKET;
2808 kif->kf_type = KF_TYPE_PIPE;
2812 kif->kf_type = KF_TYPE_FIFO;
2817 kif->kf_type = KF_TYPE_KQUEUE;
2821 kif->kf_type = KF_TYPE_CRYPTO;
2825 kif->kf_type = KF_TYPE_MQUEUE;
2829 kif->kf_type = KF_TYPE_SHM;
2834 kif->kf_type = KF_TYPE_SEM;
2838 kif->kf_type = KF_TYPE_PTS;
2843 kif->kf_type = KF_TYPE_UNKNOWN;
2846 kif->kf_ref_count = fp->f_count;
2847 if (fp->f_flag & FREAD)
2848 kif->kf_flags |= KF_FLAG_READ;
2849 if (fp->f_flag & FWRITE)
2850 kif->kf_flags |= KF_FLAG_WRITE;
2851 if (fp->f_flag & FAPPEND)
2852 kif->kf_flags |= KF_FLAG_APPEND;
2853 if (fp->f_flag & FASYNC)
2854 kif->kf_flags |= KF_FLAG_ASYNC;
2855 if (fp->f_flag & FFSYNC)
2856 kif->kf_flags |= KF_FLAG_FSYNC;
2857 if (fp->f_flag & FNONBLOCK)
2858 kif->kf_flags |= KF_FLAG_NONBLOCK;
2859 if (fp->f_flag & O_DIRECT)
2860 kif->kf_flags |= KF_FLAG_DIRECT;
2861 if (fp->f_flag & FHASLOCK)
2862 kif->kf_flags |= KF_FLAG_HASLOCK;
2863 kif->kf_offset = fp->f_offset;
2866 switch (vp->v_type) {
2868 kif->kf_vnode_type = KF_VTYPE_VNON;
2871 kif->kf_vnode_type = KF_VTYPE_VREG;
2874 kif->kf_vnode_type = KF_VTYPE_VDIR;
2877 kif->kf_vnode_type = KF_VTYPE_VBLK;
2880 kif->kf_vnode_type = KF_VTYPE_VCHR;
2883 kif->kf_vnode_type = KF_VTYPE_VLNK;
2886 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2889 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2892 kif->kf_vnode_type = KF_VTYPE_VBAD;
2895 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2899 * It is OK to drop the filedesc lock here as we will
2900 * re-validate and re-evaluate its properties when
2901 * the loop continues.
2905 FILEDESC_SUNLOCK(fdp);
2906 vn_fullpath(curthread, vp, &fullpath, &freepath);
2907 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2909 VFS_UNLOCK_GIANT(vfslocked);
2910 strlcpy(kif->kf_path, fullpath,
2911 sizeof(kif->kf_path));
2912 if (freepath != NULL)
2913 free(freepath, M_TEMP);
2914 FILEDESC_SLOCK(fdp);
2917 struct sockaddr *sa;
2919 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2920 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2921 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2924 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2925 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2926 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2929 kif->kf_sock_domain =
2930 so->so_proto->pr_domain->dom_family;
2931 kif->kf_sock_type = so->so_type;
2932 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2935 strlcpy(kif->kf_path, tty_devname(tp),
2936 sizeof(kif->kf_path));
2939 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
2940 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2944 FILEDESC_SUNLOCK(fdp);
2950 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2951 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2952 #endif /* COMPAT_FREEBSD7 */
2954 #ifdef KINFO_FILE_SIZE
2955 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2959 export_vnode_for_sysctl(struct vnode *vp, int type,
2960 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2963 char *fullpath, *freepath;
2966 bzero(kif, sizeof(*kif));
2970 kif->kf_type = KF_TYPE_VNODE;
2971 /* This function only handles directories. */
2972 if (vp->v_type != VDIR) {
2976 kif->kf_vnode_type = KF_VTYPE_VDIR;
2979 * This is not a true file descriptor, so we set a bogus refcount
2980 * and offset to indicate these fields should be ignored.
2982 kif->kf_ref_count = -1;
2983 kif->kf_offset = -1;
2987 FILEDESC_SUNLOCK(fdp);
2988 vn_fullpath(curthread, vp, &fullpath, &freepath);
2989 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2991 VFS_UNLOCK_GIANT(vfslocked);
2992 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2993 if (freepath != NULL)
2994 free(freepath, M_TEMP);
2995 /* Pack record size down */
2996 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2997 strlen(kif->kf_path) + 1;
2998 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2999 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3000 FILEDESC_SLOCK(fdp);
3005 * Get per-process file descriptors for use by procstat(1), et al.
3008 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3010 char *fullpath, *freepath;
3011 struct kinfo_file *kif;
3012 struct filedesc *fdp;
3013 int error, i, *name;
3014 struct shmfd *shmfd;
3024 if ((p = pfind((pid_t)name[0])) == NULL)
3026 if ((error = p_candebug(curthread, p))) {
3034 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3035 FILEDESC_SLOCK(fdp);
3036 if (fdp->fd_cdir != NULL)
3037 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3039 if (fdp->fd_rdir != NULL)
3040 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3042 if (fdp->fd_jdir != NULL)
3043 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3045 for (i = 0; i < fdp->fd_nfiles; i++) {
3046 if ((fp = fdp->fd_ofiles[i]) == NULL)
3048 bzero(kif, sizeof(*kif));
3054 switch (fp->f_type) {
3056 kif->kf_type = KF_TYPE_VNODE;
3061 kif->kf_type = KF_TYPE_SOCKET;
3066 kif->kf_type = KF_TYPE_PIPE;
3070 kif->kf_type = KF_TYPE_FIFO;
3075 kif->kf_type = KF_TYPE_KQUEUE;
3079 kif->kf_type = KF_TYPE_CRYPTO;
3083 kif->kf_type = KF_TYPE_MQUEUE;
3087 kif->kf_type = KF_TYPE_SHM;
3092 kif->kf_type = KF_TYPE_SEM;
3096 kif->kf_type = KF_TYPE_PTS;
3101 kif->kf_type = KF_TYPE_UNKNOWN;
3104 kif->kf_ref_count = fp->f_count;
3105 if (fp->f_flag & FREAD)
3106 kif->kf_flags |= KF_FLAG_READ;
3107 if (fp->f_flag & FWRITE)
3108 kif->kf_flags |= KF_FLAG_WRITE;
3109 if (fp->f_flag & FAPPEND)
3110 kif->kf_flags |= KF_FLAG_APPEND;
3111 if (fp->f_flag & FASYNC)
3112 kif->kf_flags |= KF_FLAG_ASYNC;
3113 if (fp->f_flag & FFSYNC)
3114 kif->kf_flags |= KF_FLAG_FSYNC;
3115 if (fp->f_flag & FNONBLOCK)
3116 kif->kf_flags |= KF_FLAG_NONBLOCK;
3117 if (fp->f_flag & O_DIRECT)
3118 kif->kf_flags |= KF_FLAG_DIRECT;
3119 if (fp->f_flag & FHASLOCK)
3120 kif->kf_flags |= KF_FLAG_HASLOCK;
3121 kif->kf_offset = fp->f_offset;
3124 switch (vp->v_type) {
3126 kif->kf_vnode_type = KF_VTYPE_VNON;
3129 kif->kf_vnode_type = KF_VTYPE_VREG;
3132 kif->kf_vnode_type = KF_VTYPE_VDIR;
3135 kif->kf_vnode_type = KF_VTYPE_VBLK;
3138 kif->kf_vnode_type = KF_VTYPE_VCHR;
3141 kif->kf_vnode_type = KF_VTYPE_VLNK;
3144 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3147 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3150 kif->kf_vnode_type = KF_VTYPE_VBAD;
3153 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3157 * It is OK to drop the filedesc lock here as we will
3158 * re-validate and re-evaluate its properties when
3159 * the loop continues.
3163 FILEDESC_SUNLOCK(fdp);
3164 vn_fullpath(curthread, vp, &fullpath, &freepath);
3165 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3167 VFS_UNLOCK_GIANT(vfslocked);
3168 strlcpy(kif->kf_path, fullpath,
3169 sizeof(kif->kf_path));
3170 if (freepath != NULL)
3171 free(freepath, M_TEMP);
3172 FILEDESC_SLOCK(fdp);
3175 struct sockaddr *sa;
3177 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3178 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3179 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3182 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3183 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3184 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3187 kif->kf_sock_domain =
3188 so->so_proto->pr_domain->dom_family;
3189 kif->kf_sock_type = so->so_type;
3190 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3193 strlcpy(kif->kf_path, tty_devname(tp),
3194 sizeof(kif->kf_path));
3197 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3198 /* Pack record size down */
3199 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3200 strlen(kif->kf_path) + 1;
3201 kif->kf_structsize = roundup(kif->kf_structsize,
3203 oldidx = req->oldidx;
3204 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3206 if (error == ENOMEM) {
3208 * The hack to keep the ABI of sysctl
3209 * kern.proc.filedesc intact, but not
3210 * to account a partially copied
3211 * kinfo_file into the oldidx.
3213 req->oldidx = oldidx;
3219 FILEDESC_SUNLOCK(fdp);
3225 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3226 sysctl_kern_proc_filedesc, "Process filedesc entries");
3230 * For the purposes of debugging, generate a human-readable string for the
3234 file_type_to_name(short type)
3264 * For the purposes of debugging, identify a process (if any, perhaps one of
3265 * many) that references the passed file in its file descriptor array. Return
3268 static struct proc *
3269 file_to_first_proc(struct file *fp)
3271 struct filedesc *fdp;
3275 FOREACH_PROC_IN_SYSTEM(p) {
3276 if (p->p_state == PRS_NEW)
3281 for (n = 0; n < fdp->fd_nfiles; n++) {
3282 if (fp == fdp->fd_ofiles[n])
3290 db_print_file(struct file *fp, int header)
3295 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3296 "File", "Type", "Data", "Flag", "GCFl", "Count",
3297 "MCount", "Vnode", "FPID", "FCmd");
3298 p = file_to_first_proc(fp);
3299 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3300 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3301 0, fp->f_count, 0, fp->f_vnode,
3302 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3305 DB_SHOW_COMMAND(file, db_show_file)
3310 db_printf("usage: show file <addr>\n");
3313 fp = (struct file *)addr;
3314 db_print_file(fp, 1);
3317 DB_SHOW_COMMAND(files, db_show_files)
3319 struct filedesc *fdp;
3326 FOREACH_PROC_IN_SYSTEM(p) {
3327 if (p->p_state == PRS_NEW)
3329 if ((fdp = p->p_fd) == NULL)
3331 for (n = 0; n < fdp->fd_nfiles; ++n) {
3332 if ((fp = fdp->fd_ofiles[n]) == NULL)
3334 db_print_file(fp, header);
3341 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3342 &maxfilesperproc, 0, "Maximum files allowed open per process");
3344 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3345 &maxfiles, 0, "Maximum number of files");
3347 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3348 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3352 filelistinit(void *dummy)
3355 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3356 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3357 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3358 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3360 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3362 /*-------------------------------------------------------------------*/
3365 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3372 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3379 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3386 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3393 badfo_kqfilter(struct file *fp, struct knote *kn)
3400 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3407 badfo_close(struct file *fp, struct thread *td)
3413 struct fileops badfileops = {
3414 .fo_read = badfo_readwrite,
3415 .fo_write = badfo_readwrite,
3416 .fo_truncate = badfo_truncate,
3417 .fo_ioctl = badfo_ioctl,
3418 .fo_poll = badfo_poll,
3419 .fo_kqfilter = badfo_kqfilter,
3420 .fo_stat = badfo_stat,
3421 .fo_close = badfo_close,
3425 /*-------------------------------------------------------------------*/
3428 * File Descriptor pseudo-device driver (/dev/fd/).
3430 * Opening minor device N dup()s the file (if any) connected to file
3431 * descriptor N belonging to the calling process. Note that this driver
3432 * consists of only the ``open()'' routine, because all subsequent
3433 * references to this file will be direct to the other driver.
3435 * XXX: we could give this one a cloning event handler if necessary.
3440 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3444 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3445 * the file descriptor being sought for duplication. The error
3446 * return ensures that the vnode for this device will be released
3447 * by vn_open. Open will detect this special error and take the
3448 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3449 * will simply report the error.
3451 td->td_dupfd = dev2unit(dev);
3455 static struct cdevsw fildesc_cdevsw = {
3456 .d_version = D_VERSION,
3462 fildesc_drvinit(void *unused)
3466 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3467 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3468 make_dev_alias(dev, "stdin");
3469 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3470 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3471 make_dev_alias(dev, "stdout");
3472 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3473 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3474 make_dev_alias(dev, "stderr");
3477 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);