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;
436 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
441 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
446 if ((fp = fdtofp(fd, fdp)) == NULL) {
447 FILEDESC_SUNLOCK(fdp);
451 pop = &fdp->fd_ofileflags[fd];
452 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
453 FILEDESC_SUNLOCK(fdp);
458 if ((fp = fdtofp(fd, fdp)) == NULL) {
459 FILEDESC_XUNLOCK(fdp);
463 pop = &fdp->fd_ofileflags[fd];
464 *pop = (*pop &~ UF_EXCLOSE) |
465 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
466 FILEDESC_XUNLOCK(fdp);
471 if ((fp = fdtofp(fd, fdp)) == NULL) {
472 FILEDESC_SUNLOCK(fdp);
476 td->td_retval[0] = OFLAGS(fp->f_flag);
477 FILEDESC_SUNLOCK(fdp);
482 if ((fp = fdtofp(fd, fdp)) == NULL) {
483 FILEDESC_SUNLOCK(fdp);
488 FILEDESC_SUNLOCK(fdp);
490 tmp = flg = fp->f_flag;
492 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
493 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
494 tmp = fp->f_flag & FNONBLOCK;
495 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
500 tmp = fp->f_flag & FASYNC;
501 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
506 atomic_clear_int(&fp->f_flag, FNONBLOCK);
508 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
514 if ((fp = fdtofp(fd, fdp)) == NULL) {
515 FILEDESC_SUNLOCK(fdp);
520 FILEDESC_SUNLOCK(fdp);
521 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
523 td->td_retval[0] = tmp;
529 if ((fp = fdtofp(fd, fdp)) == NULL) {
530 FILEDESC_SUNLOCK(fdp);
535 FILEDESC_SUNLOCK(fdp);
537 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
542 error = priv_check(td, PRIV_NFS_LOCKD);
550 /* FALLTHROUGH F_SETLK */
555 if ((fp = fdtofp(fd, fdp)) == NULL) {
556 FILEDESC_SUNLOCK(fdp);
560 if (fp->f_type != DTYPE_VNODE) {
561 FILEDESC_SUNLOCK(fdp);
565 flp = (struct flock *)arg;
566 if (flp->l_whence == SEEK_CUR) {
567 if (fp->f_offset < 0 ||
569 fp->f_offset > OFF_MAX - flp->l_start)) {
570 FILEDESC_SUNLOCK(fdp);
574 flp->l_start += fp->f_offset;
578 * VOP_ADVLOCK() may block.
581 FILEDESC_SUNLOCK(fdp);
583 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
584 switch (flp->l_type) {
586 if ((fp->f_flag & FREAD) == 0) {
590 PROC_LOCK(p->p_leader);
591 p->p_leader->p_flag |= P_ADVLOCK;
592 PROC_UNLOCK(p->p_leader);
593 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
597 if ((fp->f_flag & FWRITE) == 0) {
601 PROC_LOCK(p->p_leader);
602 p->p_leader->p_flag |= P_ADVLOCK;
603 PROC_UNLOCK(p->p_leader);
604 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
608 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
613 * Temporary api for testing remote lock
616 if (flg != F_REMOTE) {
620 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
621 F_UNLCKSYS, flp, flg);
627 VFS_UNLOCK_GIANT(vfslocked);
629 /* Check for race with close */
631 if ((unsigned) fd >= fdp->fd_nfiles ||
632 fp != fdp->fd_ofiles[fd]) {
633 FILEDESC_SUNLOCK(fdp);
634 flp->l_whence = SEEK_SET;
637 flp->l_type = F_UNLCK;
638 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
639 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
640 F_UNLCK, flp, F_POSIX);
641 VFS_UNLOCK_GIANT(vfslocked);
644 FILEDESC_SUNLOCK(fdp);
650 if ((fp = fdtofp(fd, fdp)) == NULL) {
651 FILEDESC_SUNLOCK(fdp);
655 if (fp->f_type != DTYPE_VNODE) {
656 FILEDESC_SUNLOCK(fdp);
660 flp = (struct flock *)arg;
661 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
662 flp->l_type != F_UNLCK) {
663 FILEDESC_SUNLOCK(fdp);
667 if (flp->l_whence == SEEK_CUR) {
668 if ((flp->l_start > 0 &&
669 fp->f_offset > OFF_MAX - flp->l_start) ||
671 fp->f_offset < OFF_MIN - flp->l_start)) {
672 FILEDESC_SUNLOCK(fdp);
676 flp->l_start += fp->f_offset;
679 * VOP_ADVLOCK() may block.
682 FILEDESC_SUNLOCK(fdp);
684 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
685 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
687 VFS_UNLOCK_GIANT(vfslocked);
693 arg = arg ? 128 * 1024: 0;
697 if ((fp = fdtofp(fd, fdp)) == NULL) {
698 FILEDESC_SUNLOCK(fdp);
702 if (fp->f_type != DTYPE_VNODE) {
703 FILEDESC_SUNLOCK(fdp);
708 FILEDESC_SUNLOCK(fdp);
711 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
712 error = vn_lock(vp, LK_SHARED);
714 goto readahead_vnlock_fail;
715 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
717 fp->f_seqcount = (arg + bsize - 1) / bsize;
719 new = old = fp->f_flag;
721 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
722 readahead_vnlock_fail:
723 VFS_UNLOCK_GIANT(vfslocked);
727 new = old = fp->f_flag;
729 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
738 VFS_UNLOCK_GIANT(vfslocked);
743 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
746 do_dup(struct thread *td, int flags, int old, int new,
749 struct filedesc *fdp;
753 int error, holdleaders, maxfd;
759 * Verify we have a valid descriptor to dup from and possibly to
760 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
761 * return EINVAL when the new descriptor is out of bounds.
766 return (flags & DUP_FCNTL ? EINVAL : EBADF);
768 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
771 return (flags & DUP_FCNTL ? EINVAL : EMFILE);
774 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
775 FILEDESC_XUNLOCK(fdp);
778 if (flags & DUP_FIXED && old == new) {
780 FILEDESC_XUNLOCK(fdp);
783 fp = fdp->fd_ofiles[old];
787 * If the caller specified a file descriptor, make sure the file
788 * table is large enough to hold it, and grab it. Otherwise, just
789 * allocate a new descriptor the usual way. Since the filedesc
790 * lock may be temporarily dropped in the process, we have to look
793 if (flags & DUP_FIXED) {
794 if (new >= fdp->fd_nfiles)
795 fdgrowtable(fdp, new + 1);
796 if (fdp->fd_ofiles[new] == NULL)
799 if ((error = fdalloc(td, new, &new)) != 0) {
800 FILEDESC_XUNLOCK(fdp);
807 * If the old file changed out from under us then treat it as a
808 * bad file descriptor. Userland should do its own locking to
811 if (fdp->fd_ofiles[old] != fp) {
812 /* we've allocated a descriptor which we won't use */
813 if (fdp->fd_ofiles[new] == NULL)
815 FILEDESC_XUNLOCK(fdp);
820 ("new fd is same as old"));
823 * Save info on the descriptor being overwritten. We cannot close
824 * it without introducing an ownership race for the slot, since we
825 * need to drop the filedesc lock to call closef().
827 * XXX this duplicates parts of close().
829 delfp = fdp->fd_ofiles[new];
832 if (td->td_proc->p_fdtol != NULL) {
834 * Ask fdfree() to sleep to ensure that all relevant
835 * process leaders can be traversed in closef().
837 fdp->fd_holdleaderscount++;
843 * Duplicate the source descriptor
845 fdp->fd_ofiles[new] = fp;
846 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
847 if (new > fdp->fd_lastfile)
848 fdp->fd_lastfile = new;
852 * If we dup'd over a valid file, we now own the reference to it
853 * and must dispose of it using closef() semantics (as if a
854 * close() were performed on it).
856 * XXX this duplicates parts of close().
859 knote_fdclose(td, new);
860 if (delfp->f_type == DTYPE_MQUEUE)
861 mq_fdclose(td, new, delfp);
862 FILEDESC_XUNLOCK(fdp);
863 (void) closef(delfp, td);
866 fdp->fd_holdleaderscount--;
867 if (fdp->fd_holdleaderscount == 0 &&
868 fdp->fd_holdleaderswakeup != 0) {
869 fdp->fd_holdleaderswakeup = 0;
870 wakeup(&fdp->fd_holdleaderscount);
872 FILEDESC_XUNLOCK(fdp);
875 FILEDESC_XUNLOCK(fdp);
881 * If sigio is on the list associated with a process or process group,
882 * disable signalling from the device, remove sigio from the list and
886 funsetown(struct sigio **sigiop)
896 *(sigio->sio_myref) = NULL;
897 if ((sigio)->sio_pgid < 0) {
898 struct pgrp *pg = (sigio)->sio_pgrp;
900 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
904 struct proc *p = (sigio)->sio_proc;
906 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
911 crfree(sigio->sio_ucred);
912 free(sigio, M_SIGIO);
916 * Free a list of sigio structures.
917 * We only need to lock the SIGIO_LOCK because we have made ourselves
918 * inaccessible to callers of fsetown and therefore do not need to lock
919 * the proc or pgrp struct for the list manipulation.
922 funsetownlst(struct sigiolst *sigiolst)
928 sigio = SLIST_FIRST(sigiolst);
935 * Every entry of the list should belong
936 * to a single proc or pgrp.
938 if (sigio->sio_pgid < 0) {
939 pg = sigio->sio_pgrp;
940 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
941 } else /* if (sigio->sio_pgid > 0) */ {
943 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
947 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
948 *(sigio->sio_myref) = NULL;
950 KASSERT(sigio->sio_pgid < 0,
951 ("Proc sigio in pgrp sigio list"));
952 KASSERT(sigio->sio_pgrp == pg,
953 ("Bogus pgrp in sigio list"));
955 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
958 } else /* if (p != NULL) */ {
959 KASSERT(sigio->sio_pgid > 0,
960 ("Pgrp sigio in proc sigio list"));
961 KASSERT(sigio->sio_proc == p,
962 ("Bogus proc in sigio list"));
964 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
969 crfree(sigio->sio_ucred);
970 free(sigio, M_SIGIO);
977 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
979 * After permission checking, add a sigio structure to the sigio list for
980 * the process or process group.
983 fsetown(pid_t pgid, struct sigio **sigiop)
997 /* Allocate and fill in the new sigio out of locks. */
998 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
999 sigio->sio_pgid = pgid;
1000 sigio->sio_ucred = crhold(curthread->td_ucred);
1001 sigio->sio_myref = sigiop;
1003 sx_slock(&proctree_lock);
1012 * Policy - Don't allow a process to FSETOWN a process
1013 * in another session.
1015 * Remove this test to allow maximum flexibility or
1016 * restrict FSETOWN to the current process or process
1017 * group for maximum safety.
1020 if (proc->p_session != curthread->td_proc->p_session) {
1026 } else /* if (pgid < 0) */ {
1027 pgrp = pgfind(-pgid);
1035 * Policy - Don't allow a process to FSETOWN a process
1036 * in another session.
1038 * Remove this test to allow maximum flexibility or
1039 * restrict FSETOWN to the current process or process
1040 * group for maximum safety.
1042 if (pgrp->pg_session != curthread->td_proc->p_session) {
1053 * Since funsetownlst() is called without the proctree
1054 * locked, we need to check for P_WEXIT.
1055 * XXX: is ESRCH correct?
1057 if ((proc->p_flag & P_WEXIT) != 0) {
1062 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1063 sigio->sio_proc = proc;
1067 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1068 sigio->sio_pgrp = pgrp;
1071 sx_sunlock(&proctree_lock);
1078 sx_sunlock(&proctree_lock);
1079 crfree(sigio->sio_ucred);
1080 free(sigio, M_SIGIO);
1085 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1089 struct sigio **sigiop;
1094 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1100 * Close a file descriptor.
1102 #ifndef _SYS_SYSPROTO_H_
1111 struct close_args *uap;
1114 return (kern_close(td, uap->fd));
1122 struct filedesc *fdp;
1129 fdp = td->td_proc->p_fd;
1131 AUDIT_SYSCLOSE(td, fd);
1133 FILEDESC_XLOCK(fdp);
1134 if ((unsigned)fd >= fdp->fd_nfiles ||
1135 (fp = fdp->fd_ofiles[fd]) == NULL) {
1136 FILEDESC_XUNLOCK(fdp);
1139 fdp->fd_ofiles[fd] = NULL;
1140 fdp->fd_ofileflags[fd] = 0;
1142 if (td->td_proc->p_fdtol != NULL) {
1144 * Ask fdfree() to sleep to ensure that all relevant
1145 * process leaders can be traversed in closef().
1147 fdp->fd_holdleaderscount++;
1152 * We now hold the fp reference that used to be owned by the
1153 * descriptor array. We have to unlock the FILEDESC *AFTER*
1154 * knote_fdclose to prevent a race of the fd getting opened, a knote
1155 * added, and deleteing a knote for the new fd.
1157 knote_fdclose(td, fd);
1158 if (fp->f_type == DTYPE_MQUEUE)
1159 mq_fdclose(td, fd, fp);
1160 FILEDESC_XUNLOCK(fdp);
1162 error = closef(fp, td);
1164 FILEDESC_XLOCK(fdp);
1165 fdp->fd_holdleaderscount--;
1166 if (fdp->fd_holdleaderscount == 0 &&
1167 fdp->fd_holdleaderswakeup != 0) {
1168 fdp->fd_holdleaderswakeup = 0;
1169 wakeup(&fdp->fd_holdleaderscount);
1171 FILEDESC_XUNLOCK(fdp);
1177 * Close open file descriptors.
1179 #ifndef _SYS_SYSPROTO_H_
1180 struct closefrom_args {
1186 closefrom(struct thread *td, struct closefrom_args *uap)
1188 struct filedesc *fdp;
1191 fdp = td->td_proc->p_fd;
1192 AUDIT_ARG_FD(uap->lowfd);
1195 * Treat negative starting file descriptor values identical to
1196 * closefrom(0) which closes all files.
1200 FILEDESC_SLOCK(fdp);
1201 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1202 if (fdp->fd_ofiles[fd] != NULL) {
1203 FILEDESC_SUNLOCK(fdp);
1204 (void)kern_close(td, fd);
1205 FILEDESC_SLOCK(fdp);
1208 FILEDESC_SUNLOCK(fdp);
1212 #if defined(COMPAT_43)
1214 * Return status information about a file descriptor.
1216 #ifndef _SYS_SYSPROTO_H_
1217 struct ofstat_args {
1224 ofstat(struct thread *td, struct ofstat_args *uap)
1230 error = kern_fstat(td, uap->fd, &ub);
1233 error = copyout(&oub, uap->sb, sizeof(oub));
1237 #endif /* COMPAT_43 */
1240 * Return status information about a file descriptor.
1242 #ifndef _SYS_SYSPROTO_H_
1250 fstat(struct thread *td, struct fstat_args *uap)
1255 error = kern_fstat(td, uap->fd, &ub);
1257 error = copyout(&ub, uap->sb, sizeof(ub));
1262 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1269 if ((error = fget(td, fd, &fp)) != 0)
1272 AUDIT_ARG_FILE(td->td_proc, fp);
1274 error = fo_stat(fp, sbp, td->td_ucred, td);
1277 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1284 * Return status information about a file descriptor.
1286 #ifndef _SYS_SYSPROTO_H_
1287 struct nfstat_args {
1294 nfstat(struct thread *td, struct nfstat_args *uap)
1300 error = kern_fstat(td, uap->fd, &ub);
1302 cvtnstat(&ub, &nub);
1303 error = copyout(&nub, uap->sb, sizeof(nub));
1309 * Return pathconf information about a file descriptor.
1311 #ifndef _SYS_SYSPROTO_H_
1312 struct fpathconf_args {
1319 fpathconf(struct thread *td, struct fpathconf_args *uap)
1325 if ((error = fget(td, uap->fd, &fp)) != 0)
1328 /* If asynchronous I/O is available, it works for all descriptors. */
1329 if (uap->name == _PC_ASYNC_IO) {
1330 td->td_retval[0] = async_io_version;
1336 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1337 vn_lock(vp, LK_SHARED | LK_RETRY);
1338 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1340 VFS_UNLOCK_GIANT(vfslocked);
1341 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1342 if (uap->name != _PC_PIPE_BUF) {
1345 td->td_retval[0] = PIPE_BUF;
1357 * Grow the file table to accomodate (at least) nfd descriptors. This may
1358 * block and drop the filedesc lock, but it will reacquire it before
1362 fdgrowtable(struct filedesc *fdp, int nfd)
1364 struct filedesc0 *fdp0;
1365 struct freetable *fo;
1366 struct file **ntable;
1367 struct file **otable;
1369 int nnfiles, onfiles;
1372 FILEDESC_XLOCK_ASSERT(fdp);
1374 KASSERT(fdp->fd_nfiles > 0,
1375 ("zero-length file table"));
1377 /* compute the size of the new table */
1378 onfiles = fdp->fd_nfiles;
1379 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1380 if (nnfiles <= onfiles)
1381 /* the table is already large enough */
1384 /* allocate a new table and (if required) new bitmaps */
1385 FILEDESC_XUNLOCK(fdp);
1386 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1387 M_FILEDESC, M_ZERO | M_WAITOK);
1388 nfileflags = (char *)&ntable[nnfiles];
1389 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1390 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1391 M_FILEDESC, M_ZERO | M_WAITOK);
1394 FILEDESC_XLOCK(fdp);
1397 * We now have new tables ready to go. Since we dropped the
1398 * filedesc lock to call malloc(), watch out for a race.
1400 onfiles = fdp->fd_nfiles;
1401 if (onfiles >= nnfiles) {
1402 /* we lost the race, but that's OK */
1403 free(ntable, M_FILEDESC);
1405 free(nmap, M_FILEDESC);
1408 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1409 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1410 otable = fdp->fd_ofiles;
1411 fdp->fd_ofileflags = nfileflags;
1412 fdp->fd_ofiles = ntable;
1414 * We must preserve ofiles until the process exits because we can't
1415 * be certain that no threads have references to the old table via
1418 if (onfiles > NDFILE) {
1419 fo = (struct freetable *)&otable[onfiles];
1420 fdp0 = (struct filedesc0 *)fdp;
1421 fo->ft_table = otable;
1422 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1424 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1425 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1426 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1427 free(fdp->fd_map, M_FILEDESC);
1430 fdp->fd_nfiles = nnfiles;
1434 * Allocate a file descriptor for the process.
1437 fdalloc(struct thread *td, int minfd, int *result)
1439 struct proc *p = td->td_proc;
1440 struct filedesc *fdp = p->p_fd;
1443 FILEDESC_XLOCK_ASSERT(fdp);
1445 if (fdp->fd_freefile > minfd)
1446 minfd = fdp->fd_freefile;
1449 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1453 * Search the bitmap for a free descriptor. If none is found, try
1454 * to grow the file table. Keep at it until we either get a file
1455 * descriptor or run into process or system limits; fdgrowtable()
1456 * may drop the filedesc lock, so we're in a race.
1459 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1462 if (fd < fdp->fd_nfiles)
1464 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1468 * Perform some sanity checks, then mark the file descriptor as
1469 * used and return it to the caller.
1471 KASSERT(!fdisused(fdp, fd),
1472 ("fd_first_free() returned non-free descriptor"));
1473 KASSERT(fdp->fd_ofiles[fd] == NULL,
1474 ("free descriptor isn't"));
1475 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1482 * Check to see whether n user file descriptors are available to the process
1486 fdavail(struct thread *td, int n)
1488 struct proc *p = td->td_proc;
1489 struct filedesc *fdp = td->td_proc->p_fd;
1493 FILEDESC_LOCK_ASSERT(fdp);
1496 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1498 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1500 last = min(fdp->fd_nfiles, lim);
1501 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1502 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1503 if (*fpp == NULL && --n <= 0)
1510 * Create a new open file structure and allocate a file decriptor for the
1511 * process that refers to it. We add one reference to the file for the
1512 * descriptor table and one reference for resultfp. This is to prevent us
1513 * being preempted and the entry in the descriptor table closed after we
1514 * release the FILEDESC lock.
1517 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1519 struct proc *p = td->td_proc;
1522 int maxuserfiles = maxfiles - (maxfiles / 20);
1523 static struct timeval lastfail;
1526 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1527 if ((openfiles >= maxuserfiles &&
1528 priv_check(td, PRIV_MAXFILES) != 0) ||
1529 openfiles >= maxfiles) {
1530 if (ppsratecheck(&lastfail, &curfail, 1)) {
1531 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1532 td->td_ucred->cr_ruid);
1534 uma_zfree(file_zone, fp);
1537 atomic_add_int(&openfiles, 1);
1540 * If the process has file descriptor zero open, add the new file
1541 * descriptor to the list of open files at that point, otherwise
1542 * put it at the front of the list of open files.
1544 refcount_init(&fp->f_count, 1);
1547 fp->f_cred = crhold(td->td_ucred);
1548 fp->f_ops = &badfileops;
1551 FILEDESC_XLOCK(p->p_fd);
1552 if ((error = fdalloc(td, 0, &i))) {
1553 FILEDESC_XUNLOCK(p->p_fd);
1559 p->p_fd->fd_ofiles[i] = fp;
1560 FILEDESC_XUNLOCK(p->p_fd);
1569 * Build a new filedesc structure from another.
1570 * Copy the current, root, and jail root vnode references.
1573 fdinit(struct filedesc *fdp)
1575 struct filedesc0 *newfdp;
1577 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1578 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1580 FILEDESC_XLOCK(fdp);
1581 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1582 if (newfdp->fd_fd.fd_cdir)
1583 VREF(newfdp->fd_fd.fd_cdir);
1584 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1585 if (newfdp->fd_fd.fd_rdir)
1586 VREF(newfdp->fd_fd.fd_rdir);
1587 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1588 if (newfdp->fd_fd.fd_jdir)
1589 VREF(newfdp->fd_fd.fd_jdir);
1590 FILEDESC_XUNLOCK(fdp);
1593 /* Create the file descriptor table. */
1594 newfdp->fd_fd.fd_refcnt = 1;
1595 newfdp->fd_fd.fd_holdcnt = 1;
1596 newfdp->fd_fd.fd_cmask = CMASK;
1597 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1598 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1599 newfdp->fd_fd.fd_nfiles = NDFILE;
1600 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1601 newfdp->fd_fd.fd_lastfile = -1;
1602 return (&newfdp->fd_fd);
1605 static struct filedesc *
1606 fdhold(struct proc *p)
1608 struct filedesc *fdp;
1610 mtx_lock(&fdesc_mtx);
1614 mtx_unlock(&fdesc_mtx);
1619 fddrop(struct filedesc *fdp)
1621 struct filedesc0 *fdp0;
1622 struct freetable *ft;
1625 mtx_lock(&fdesc_mtx);
1626 i = --fdp->fd_holdcnt;
1627 mtx_unlock(&fdesc_mtx);
1631 FILEDESC_LOCK_DESTROY(fdp);
1632 fdp0 = (struct filedesc0 *)fdp;
1633 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1634 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1635 free(ft->ft_table, M_FILEDESC);
1637 free(fdp, M_FILEDESC);
1641 * Share a filedesc structure.
1644 fdshare(struct filedesc *fdp)
1647 FILEDESC_XLOCK(fdp);
1649 FILEDESC_XUNLOCK(fdp);
1654 * Unshare a filedesc structure, if necessary by making a copy
1657 fdunshare(struct proc *p, struct thread *td)
1660 FILEDESC_XLOCK(p->p_fd);
1661 if (p->p_fd->fd_refcnt > 1) {
1662 struct filedesc *tmp;
1664 FILEDESC_XUNLOCK(p->p_fd);
1665 tmp = fdcopy(p->p_fd);
1669 FILEDESC_XUNLOCK(p->p_fd);
1673 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1674 * this is to ease callers, not catch errors.
1677 fdcopy(struct filedesc *fdp)
1679 struct filedesc *newfdp;
1682 /* Certain daemons might not have file descriptors. */
1686 newfdp = fdinit(fdp);
1687 FILEDESC_SLOCK(fdp);
1688 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1689 FILEDESC_SUNLOCK(fdp);
1690 FILEDESC_XLOCK(newfdp);
1691 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1692 FILEDESC_XUNLOCK(newfdp);
1693 FILEDESC_SLOCK(fdp);
1695 /* copy everything except kqueue descriptors */
1696 newfdp->fd_freefile = -1;
1697 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1698 if (fdisused(fdp, i) &&
1699 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1700 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1701 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1702 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1703 fhold(newfdp->fd_ofiles[i]);
1704 newfdp->fd_lastfile = i;
1706 if (newfdp->fd_freefile == -1)
1707 newfdp->fd_freefile = i;
1710 newfdp->fd_cmask = fdp->fd_cmask;
1711 FILEDESC_SUNLOCK(fdp);
1712 FILEDESC_XLOCK(newfdp);
1713 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1714 if (newfdp->fd_ofiles[i] != NULL)
1716 if (newfdp->fd_freefile == -1)
1717 newfdp->fd_freefile = i;
1718 FILEDESC_XUNLOCK(newfdp);
1723 * Release a filedesc structure.
1726 fdfree(struct thread *td)
1728 struct filedesc *fdp;
1731 struct filedesc_to_leader *fdtol;
1733 struct vnode *cdir, *jdir, *rdir, *vp;
1736 /* Certain daemons might not have file descriptors. */
1737 fdp = td->td_proc->p_fd;
1741 /* Check for special need to clear POSIX style locks */
1742 fdtol = td->td_proc->p_fdtol;
1743 if (fdtol != NULL) {
1744 FILEDESC_XLOCK(fdp);
1745 KASSERT(fdtol->fdl_refcount > 0,
1746 ("filedesc_to_refcount botch: fdl_refcount=%d",
1747 fdtol->fdl_refcount));
1748 if (fdtol->fdl_refcount == 1 &&
1749 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1750 for (i = 0, fpp = fdp->fd_ofiles;
1751 i <= fdp->fd_lastfile;
1754 (*fpp)->f_type != DTYPE_VNODE)
1758 FILEDESC_XUNLOCK(fdp);
1759 lf.l_whence = SEEK_SET;
1762 lf.l_type = F_UNLCK;
1764 locked = VFS_LOCK_GIANT(vp->v_mount);
1765 (void) VOP_ADVLOCK(vp,
1766 (caddr_t)td->td_proc->
1771 VFS_UNLOCK_GIANT(locked);
1772 FILEDESC_XLOCK(fdp);
1774 fpp = fdp->fd_ofiles + i;
1778 if (fdtol->fdl_refcount == 1) {
1779 if (fdp->fd_holdleaderscount > 0 &&
1780 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1782 * close() or do_dup() has cleared a reference
1783 * in a shared file descriptor table.
1785 fdp->fd_holdleaderswakeup = 1;
1786 sx_sleep(&fdp->fd_holdleaderscount,
1787 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1790 if (fdtol->fdl_holdcount > 0) {
1792 * Ensure that fdtol->fdl_leader remains
1793 * valid in closef().
1795 fdtol->fdl_wakeup = 1;
1796 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1801 fdtol->fdl_refcount--;
1802 if (fdtol->fdl_refcount == 0 &&
1803 fdtol->fdl_holdcount == 0) {
1804 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1805 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1808 td->td_proc->p_fdtol = NULL;
1809 FILEDESC_XUNLOCK(fdp);
1811 free(fdtol, M_FILEDESC_TO_LEADER);
1813 FILEDESC_XLOCK(fdp);
1814 i = --fdp->fd_refcnt;
1815 FILEDESC_XUNLOCK(fdp);
1819 fpp = fdp->fd_ofiles;
1820 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1822 FILEDESC_XLOCK(fdp);
1825 FILEDESC_XUNLOCK(fdp);
1826 (void) closef(fp, td);
1829 FILEDESC_XLOCK(fdp);
1831 /* XXX This should happen earlier. */
1832 mtx_lock(&fdesc_mtx);
1833 td->td_proc->p_fd = NULL;
1834 mtx_unlock(&fdesc_mtx);
1836 if (fdp->fd_nfiles > NDFILE)
1837 free(fdp->fd_ofiles, M_FILEDESC);
1838 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1839 free(fdp->fd_map, M_FILEDESC);
1843 cdir = fdp->fd_cdir;
1844 fdp->fd_cdir = NULL;
1845 rdir = fdp->fd_rdir;
1846 fdp->fd_rdir = NULL;
1847 jdir = fdp->fd_jdir;
1848 fdp->fd_jdir = NULL;
1849 FILEDESC_XUNLOCK(fdp);
1852 locked = VFS_LOCK_GIANT(cdir->v_mount);
1854 VFS_UNLOCK_GIANT(locked);
1857 locked = VFS_LOCK_GIANT(rdir->v_mount);
1859 VFS_UNLOCK_GIANT(locked);
1862 locked = VFS_LOCK_GIANT(jdir->v_mount);
1864 VFS_UNLOCK_GIANT(locked);
1871 * For setugid programs, we don't want to people to use that setugidness
1872 * to generate error messages which write to a file which otherwise would
1873 * otherwise be off-limits to the process. We check for filesystems where
1874 * the vnode can change out from under us after execve (like [lin]procfs).
1876 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1877 * sufficient. We also don't check for setugidness since we know we are.
1880 is_unsafe(struct file *fp)
1882 if (fp->f_type == DTYPE_VNODE) {
1883 struct vnode *vp = fp->f_vnode;
1885 if ((vp->v_vflag & VV_PROCDEP) != 0)
1892 * Make this setguid thing safe, if at all possible.
1895 setugidsafety(struct thread *td)
1897 struct filedesc *fdp;
1900 /* Certain daemons might not have file descriptors. */
1901 fdp = td->td_proc->p_fd;
1906 * Note: fdp->fd_ofiles may be reallocated out from under us while
1907 * we are blocked in a close. Be careful!
1909 FILEDESC_XLOCK(fdp);
1910 for (i = 0; i <= fdp->fd_lastfile; i++) {
1913 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1916 knote_fdclose(td, i);
1918 * NULL-out descriptor prior to close to avoid
1919 * a race while close blocks.
1921 fp = fdp->fd_ofiles[i];
1922 fdp->fd_ofiles[i] = NULL;
1923 fdp->fd_ofileflags[i] = 0;
1925 FILEDESC_XUNLOCK(fdp);
1926 (void) closef(fp, td);
1927 FILEDESC_XLOCK(fdp);
1930 FILEDESC_XUNLOCK(fdp);
1934 * If a specific file object occupies a specific file descriptor, close the
1935 * file descriptor entry and drop a reference on the file object. This is a
1936 * convenience function to handle a subsequent error in a function that calls
1937 * falloc() that handles the race that another thread might have closed the
1938 * file descriptor out from under the thread creating the file object.
1941 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1944 FILEDESC_XLOCK(fdp);
1945 if (fdp->fd_ofiles[idx] == fp) {
1946 fdp->fd_ofiles[idx] = NULL;
1948 FILEDESC_XUNLOCK(fdp);
1951 FILEDESC_XUNLOCK(fdp);
1955 * Close any files on exec?
1958 fdcloseexec(struct thread *td)
1960 struct filedesc *fdp;
1963 /* Certain daemons might not have file descriptors. */
1964 fdp = td->td_proc->p_fd;
1968 FILEDESC_XLOCK(fdp);
1971 * We cannot cache fd_ofiles or fd_ofileflags since operations
1972 * may block and rip them out from under us.
1974 for (i = 0; i <= fdp->fd_lastfile; i++) {
1975 if (fdp->fd_ofiles[i] != NULL &&
1976 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1977 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1980 knote_fdclose(td, i);
1982 * NULL-out descriptor prior to close to avoid
1983 * a race while close blocks.
1985 fp = fdp->fd_ofiles[i];
1986 fdp->fd_ofiles[i] = NULL;
1987 fdp->fd_ofileflags[i] = 0;
1989 if (fp->f_type == DTYPE_MQUEUE)
1990 mq_fdclose(td, i, fp);
1991 FILEDESC_XUNLOCK(fdp);
1992 (void) closef(fp, td);
1993 FILEDESC_XLOCK(fdp);
1996 FILEDESC_XUNLOCK(fdp);
2000 * It is unsafe for set[ug]id processes to be started with file
2001 * descriptors 0..2 closed, as these descriptors are given implicit
2002 * significance in the Standard C library. fdcheckstd() will create a
2003 * descriptor referencing /dev/null for each of stdin, stdout, and
2004 * stderr that is not already open.
2007 fdcheckstd(struct thread *td)
2009 struct filedesc *fdp;
2010 register_t retval, save;
2011 int i, error, devnull;
2013 fdp = td->td_proc->p_fd;
2016 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2019 for (i = 0; i < 3; i++) {
2020 if (fdp->fd_ofiles[i] != NULL)
2023 save = td->td_retval[0];
2024 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2026 devnull = td->td_retval[0];
2027 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2028 td->td_retval[0] = save;
2032 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2041 * Internal form of close. Decrement reference count on file structure.
2042 * Note: td may be NULL when closing a file that was being passed in a
2045 * XXXRW: Giant is not required for the caller, but often will be held; this
2046 * makes it moderately likely the Giant will be recursed in the VFS case.
2049 closef(struct file *fp, struct thread *td)
2053 struct filedesc_to_leader *fdtol;
2054 struct filedesc *fdp;
2057 * POSIX record locking dictates that any close releases ALL
2058 * locks owned by this process. This is handled by setting
2059 * a flag in the unlock to free ONLY locks obeying POSIX
2060 * semantics, and not to free BSD-style file locks.
2061 * If the descriptor was in a message, POSIX-style locks
2062 * aren't passed with the descriptor, and the thread pointer
2063 * will be NULL. Callers should be careful only to pass a
2064 * NULL thread pointer when there really is no owning
2065 * context that might have locks, or the locks will be
2068 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2072 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2073 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2074 lf.l_whence = SEEK_SET;
2077 lf.l_type = F_UNLCK;
2078 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2079 F_UNLCK, &lf, F_POSIX);
2081 fdtol = td->td_proc->p_fdtol;
2082 if (fdtol != NULL) {
2084 * Handle special case where file descriptor table is
2085 * shared between multiple process leaders.
2087 fdp = td->td_proc->p_fd;
2088 FILEDESC_XLOCK(fdp);
2089 for (fdtol = fdtol->fdl_next;
2090 fdtol != td->td_proc->p_fdtol;
2091 fdtol = fdtol->fdl_next) {
2092 if ((fdtol->fdl_leader->p_flag &
2095 fdtol->fdl_holdcount++;
2096 FILEDESC_XUNLOCK(fdp);
2097 lf.l_whence = SEEK_SET;
2100 lf.l_type = F_UNLCK;
2102 (void) VOP_ADVLOCK(vp,
2103 (caddr_t)fdtol->fdl_leader,
2104 F_UNLCK, &lf, F_POSIX);
2105 FILEDESC_XLOCK(fdp);
2106 fdtol->fdl_holdcount--;
2107 if (fdtol->fdl_holdcount == 0 &&
2108 fdtol->fdl_wakeup != 0) {
2109 fdtol->fdl_wakeup = 0;
2113 FILEDESC_XUNLOCK(fdp);
2115 VFS_UNLOCK_GIANT(vfslocked);
2117 return (fdrop(fp, td));
2121 * Initialize the file pointer with the specified properties.
2123 * The ops are set with release semantics to be certain that the flags, type,
2124 * and data are visible when ops is. This is to prevent ops methods from being
2125 * called with bad data.
2128 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2133 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2137 fget_unlocked(struct filedesc *fdp, int fd)
2142 if (fd < 0 || fd >= fdp->fd_nfiles)
2145 * Fetch the descriptor locklessly. We avoid fdrop() races by
2146 * never raising a refcount above 0. To accomplish this we have
2147 * to use a cmpset loop rather than an atomic_add. The descriptor
2148 * must be re-verified once we acquire a reference to be certain
2149 * that the identity is still correct and we did not lose a race
2150 * due to preemption.
2153 fp = fdp->fd_ofiles[fd];
2156 count = fp->f_count;
2160 * Use an acquire barrier to prevent caching of fd_ofiles
2161 * so it is refreshed for verification.
2163 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2165 if (fp == fdp->fd_ofiles[fd])
2167 fdrop(fp, curthread);
2174 * Extract the file pointer associated with the specified descriptor for the
2175 * current user process.
2177 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2180 * If an error occured the non-zero error is returned and *fpp is set to
2181 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2182 * responsible for fdrop().
2185 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2187 struct filedesc *fdp;
2191 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2193 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2195 if (fp->f_ops == &badfileops) {
2200 * FREAD and FWRITE failure return EBADF as per POSIX.
2202 * Only one flag, or 0, may be specified.
2204 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2205 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2214 fget(struct thread *td, int fd, struct file **fpp)
2217 return(_fget(td, fd, fpp, 0));
2221 fget_read(struct thread *td, int fd, struct file **fpp)
2224 return(_fget(td, fd, fpp, FREAD));
2228 fget_write(struct thread *td, int fd, struct file **fpp)
2231 return(_fget(td, fd, fpp, FWRITE));
2235 * Like fget() but loads the underlying vnode, or returns an error if the
2236 * descriptor does not represent a vnode. Note that pipes use vnodes but
2237 * never have VM objects. The returned vnode will be vref()'d.
2239 * XXX: what about the unused flags ?
2242 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2248 if ((error = _fget(td, fd, &fp, flags)) != 0)
2250 if (fp->f_vnode == NULL) {
2262 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2265 return (_fgetvp(td, fd, vpp, 0));
2269 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2272 return (_fgetvp(td, fd, vpp, FREAD));
2277 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2280 return (_fgetvp(td, fd, vpp, FWRITE));
2285 * Like fget() but loads the underlying socket, or returns an error if the
2286 * descriptor does not represent a socket.
2288 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2291 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2292 * on their file descriptor reference to prevent the socket from being free'd
2296 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2304 if ((error = _fget(td, fd, &fp, 0)) != 0)
2306 if (fp->f_type != DTYPE_SOCKET) {
2311 *fflagp = fp->f_flag;
2322 * Drop the reference count on the socket and XXX release the SX lock in the
2323 * future. The last reference closes the socket.
2325 * Note: fputsock() is deprecated, see comment for fgetsock().
2328 fputsock(struct socket *so)
2337 * Handle the last reference to a file being closed.
2340 _fdrop(struct file *fp, struct thread *td)
2345 if (fp->f_count != 0)
2346 panic("fdrop: count %d", fp->f_count);
2347 if (fp->f_ops != &badfileops)
2348 error = fo_close(fp, td);
2350 * The f_cdevpriv cannot be assigned non-NULL value while we
2351 * are destroying the file.
2353 if (fp->f_cdevpriv != NULL)
2355 atomic_subtract_int(&openfiles, 1);
2357 uma_zfree(file_zone, fp);
2363 * Apply an advisory lock on a file descriptor.
2365 * Just attempt to get a record lock of the requested type on the entire file
2366 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2368 #ifndef _SYS_SYSPROTO_H_
2376 flock(struct thread *td, struct flock_args *uap)
2384 if ((error = fget(td, uap->fd, &fp)) != 0)
2386 if (fp->f_type != DTYPE_VNODE) {
2388 return (EOPNOTSUPP);
2392 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2393 lf.l_whence = SEEK_SET;
2396 if (uap->how & LOCK_UN) {
2397 lf.l_type = F_UNLCK;
2398 atomic_clear_int(&fp->f_flag, FHASLOCK);
2399 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2402 if (uap->how & LOCK_EX)
2403 lf.l_type = F_WRLCK;
2404 else if (uap->how & LOCK_SH)
2405 lf.l_type = F_RDLCK;
2410 atomic_set_int(&fp->f_flag, FHASLOCK);
2411 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2412 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2415 VFS_UNLOCK_GIANT(vfslocked);
2419 * Duplicate the specified descriptor to a free descriptor.
2422 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2428 * If the to-be-dup'd fd number is greater than the allowed number
2429 * of file descriptors, or the fd to be dup'd has already been
2430 * closed, then reject.
2432 FILEDESC_XLOCK(fdp);
2433 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2434 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2435 FILEDESC_XUNLOCK(fdp);
2440 * There are two cases of interest here.
2442 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2444 * For ENXIO steal away the file structure from (dfd) and store it in
2445 * (indx). (dfd) is effectively closed by this operation.
2447 * Any other error code is just returned.
2452 * Check that the mode the file is being opened for is a
2453 * subset of the mode of the existing descriptor.
2455 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2456 FILEDESC_XUNLOCK(fdp);
2459 fp = fdp->fd_ofiles[indx];
2460 fdp->fd_ofiles[indx] = wfp;
2461 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2465 FILEDESC_XUNLOCK(fdp);
2468 * We now own the reference to fp that the ofiles[]
2469 * array used to own. Release it.
2476 * Steal away the file pointer from dfd and stuff it into indx.
2478 fp = fdp->fd_ofiles[indx];
2479 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2480 fdp->fd_ofiles[dfd] = NULL;
2481 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2482 fdp->fd_ofileflags[dfd] = 0;
2486 FILEDESC_XUNLOCK(fdp);
2489 * We now own the reference to fp that the ofiles[] array
2490 * used to own. Release it.
2497 FILEDESC_XUNLOCK(fdp);
2504 * Scan all active processes and prisons to see if any of them have a current
2505 * or root directory of `olddp'. If so, replace them with the new mount point.
2508 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2510 struct filedesc *fdp;
2515 if (vrefcnt(olddp) == 1)
2518 sx_slock(&allproc_lock);
2519 FOREACH_PROC_IN_SYSTEM(p) {
2523 FILEDESC_XLOCK(fdp);
2524 if (fdp->fd_cdir == olddp) {
2526 fdp->fd_cdir = newdp;
2529 if (fdp->fd_rdir == olddp) {
2531 fdp->fd_rdir = newdp;
2534 if (fdp->fd_jdir == olddp) {
2536 fdp->fd_jdir = newdp;
2539 FILEDESC_XUNLOCK(fdp);
2542 sx_sunlock(&allproc_lock);
2543 if (rootvnode == olddp) {
2548 mtx_lock(&prison0.pr_mtx);
2549 if (prison0.pr_root == olddp) {
2551 prison0.pr_root = newdp;
2554 mtx_unlock(&prison0.pr_mtx);
2555 sx_slock(&allprison_lock);
2556 TAILQ_FOREACH(pr, &allprison, pr_list) {
2557 mtx_lock(&pr->pr_mtx);
2558 if (pr->pr_root == olddp) {
2560 pr->pr_root = newdp;
2563 mtx_unlock(&pr->pr_mtx);
2565 sx_sunlock(&allprison_lock);
2570 struct filedesc_to_leader *
2571 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2573 struct filedesc_to_leader *fdtol;
2575 fdtol = malloc(sizeof(struct filedesc_to_leader),
2576 M_FILEDESC_TO_LEADER,
2578 fdtol->fdl_refcount = 1;
2579 fdtol->fdl_holdcount = 0;
2580 fdtol->fdl_wakeup = 0;
2581 fdtol->fdl_leader = leader;
2583 FILEDESC_XLOCK(fdp);
2584 fdtol->fdl_next = old->fdl_next;
2585 fdtol->fdl_prev = old;
2586 old->fdl_next = fdtol;
2587 fdtol->fdl_next->fdl_prev = fdtol;
2588 FILEDESC_XUNLOCK(fdp);
2590 fdtol->fdl_next = fdtol;
2591 fdtol->fdl_prev = fdtol;
2597 * Get file structures globally.
2600 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2603 struct filedesc *fdp;
2608 error = sysctl_wire_old_buffer(req, 0);
2611 if (req->oldptr == NULL) {
2613 sx_slock(&allproc_lock);
2614 FOREACH_PROC_IN_SYSTEM(p) {
2615 if (p->p_state == PRS_NEW)
2620 /* overestimates sparse tables. */
2621 if (fdp->fd_lastfile > 0)
2622 n += fdp->fd_lastfile;
2625 sx_sunlock(&allproc_lock);
2626 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2629 bzero(&xf, sizeof(xf));
2630 xf.xf_size = sizeof(xf);
2631 sx_slock(&allproc_lock);
2632 FOREACH_PROC_IN_SYSTEM(p) {
2633 if (p->p_state == PRS_NEW)
2636 if (p_cansee(req->td, p) != 0) {
2640 xf.xf_pid = p->p_pid;
2641 xf.xf_uid = p->p_ucred->cr_uid;
2646 FILEDESC_SLOCK(fdp);
2647 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2648 if ((fp = fdp->fd_ofiles[n]) == NULL)
2652 xf.xf_data = fp->f_data;
2653 xf.xf_vnode = fp->f_vnode;
2654 xf.xf_type = fp->f_type;
2655 xf.xf_count = fp->f_count;
2657 xf.xf_offset = fp->f_offset;
2658 xf.xf_flag = fp->f_flag;
2659 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2663 FILEDESC_SUNLOCK(fdp);
2668 sx_sunlock(&allproc_lock);
2672 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2673 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2675 #ifdef KINFO_OFILE_SIZE
2676 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2679 #ifdef COMPAT_FREEBSD7
2681 export_vnode_for_osysctl(struct vnode *vp, int type,
2682 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2685 char *fullpath, *freepath;
2688 bzero(kif, sizeof(*kif));
2689 kif->kf_structsize = sizeof(*kif);
2693 kif->kf_type = KF_TYPE_VNODE;
2694 /* This function only handles directories. */
2695 if (vp->v_type != VDIR) {
2699 kif->kf_vnode_type = KF_VTYPE_VDIR;
2702 * This is not a true file descriptor, so we set a bogus refcount
2703 * and offset to indicate these fields should be ignored.
2705 kif->kf_ref_count = -1;
2706 kif->kf_offset = -1;
2710 FILEDESC_SUNLOCK(fdp);
2711 vn_fullpath(curthread, vp, &fullpath, &freepath);
2712 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2714 VFS_UNLOCK_GIANT(vfslocked);
2715 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2716 if (freepath != NULL)
2717 free(freepath, M_TEMP);
2718 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2719 FILEDESC_SLOCK(fdp);
2724 * Get per-process file descriptors for use by procstat(1), et al.
2727 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2729 char *fullpath, *freepath;
2730 struct kinfo_ofile *kif;
2731 struct filedesc *fdp;
2732 int error, i, *name;
2741 if ((p = pfind((pid_t)name[0])) == NULL)
2743 if ((error = p_candebug(curthread, p))) {
2751 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2752 FILEDESC_SLOCK(fdp);
2753 if (fdp->fd_cdir != NULL)
2754 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2756 if (fdp->fd_rdir != NULL)
2757 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2759 if (fdp->fd_jdir != NULL)
2760 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2762 for (i = 0; i < fdp->fd_nfiles; i++) {
2763 if ((fp = fdp->fd_ofiles[i]) == NULL)
2765 bzero(kif, sizeof(*kif));
2766 kif->kf_structsize = sizeof(*kif);
2771 switch (fp->f_type) {
2773 kif->kf_type = KF_TYPE_VNODE;
2778 kif->kf_type = KF_TYPE_SOCKET;
2783 kif->kf_type = KF_TYPE_PIPE;
2787 kif->kf_type = KF_TYPE_FIFO;
2792 kif->kf_type = KF_TYPE_KQUEUE;
2796 kif->kf_type = KF_TYPE_CRYPTO;
2800 kif->kf_type = KF_TYPE_MQUEUE;
2804 kif->kf_type = KF_TYPE_SHM;
2808 kif->kf_type = KF_TYPE_SEM;
2812 kif->kf_type = KF_TYPE_PTS;
2817 kif->kf_type = KF_TYPE_UNKNOWN;
2820 kif->kf_ref_count = fp->f_count;
2821 if (fp->f_flag & FREAD)
2822 kif->kf_flags |= KF_FLAG_READ;
2823 if (fp->f_flag & FWRITE)
2824 kif->kf_flags |= KF_FLAG_WRITE;
2825 if (fp->f_flag & FAPPEND)
2826 kif->kf_flags |= KF_FLAG_APPEND;
2827 if (fp->f_flag & FASYNC)
2828 kif->kf_flags |= KF_FLAG_ASYNC;
2829 if (fp->f_flag & FFSYNC)
2830 kif->kf_flags |= KF_FLAG_FSYNC;
2831 if (fp->f_flag & FNONBLOCK)
2832 kif->kf_flags |= KF_FLAG_NONBLOCK;
2833 if (fp->f_flag & O_DIRECT)
2834 kif->kf_flags |= KF_FLAG_DIRECT;
2835 if (fp->f_flag & FHASLOCK)
2836 kif->kf_flags |= KF_FLAG_HASLOCK;
2837 kif->kf_offset = fp->f_offset;
2840 switch (vp->v_type) {
2842 kif->kf_vnode_type = KF_VTYPE_VNON;
2845 kif->kf_vnode_type = KF_VTYPE_VREG;
2848 kif->kf_vnode_type = KF_VTYPE_VDIR;
2851 kif->kf_vnode_type = KF_VTYPE_VBLK;
2854 kif->kf_vnode_type = KF_VTYPE_VCHR;
2857 kif->kf_vnode_type = KF_VTYPE_VLNK;
2860 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2863 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2866 kif->kf_vnode_type = KF_VTYPE_VBAD;
2869 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2873 * It is OK to drop the filedesc lock here as we will
2874 * re-validate and re-evaluate its properties when
2875 * the loop continues.
2879 FILEDESC_SUNLOCK(fdp);
2880 vn_fullpath(curthread, vp, &fullpath, &freepath);
2881 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2883 VFS_UNLOCK_GIANT(vfslocked);
2884 strlcpy(kif->kf_path, fullpath,
2885 sizeof(kif->kf_path));
2886 if (freepath != NULL)
2887 free(freepath, M_TEMP);
2888 FILEDESC_SLOCK(fdp);
2891 struct sockaddr *sa;
2893 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2894 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2895 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2898 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2899 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2900 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2903 kif->kf_sock_domain =
2904 so->so_proto->pr_domain->dom_family;
2905 kif->kf_sock_type = so->so_type;
2906 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2909 strlcpy(kif->kf_path, tty_devname(tp),
2910 sizeof(kif->kf_path));
2912 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2916 FILEDESC_SUNLOCK(fdp);
2922 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2923 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2924 #endif /* COMPAT_FREEBSD7 */
2926 #ifdef KINFO_FILE_SIZE
2927 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2931 export_vnode_for_sysctl(struct vnode *vp, int type,
2932 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2935 char *fullpath, *freepath;
2938 bzero(kif, sizeof(*kif));
2942 kif->kf_type = KF_TYPE_VNODE;
2943 /* This function only handles directories. */
2944 if (vp->v_type != VDIR) {
2948 kif->kf_vnode_type = KF_VTYPE_VDIR;
2951 * This is not a true file descriptor, so we set a bogus refcount
2952 * and offset to indicate these fields should be ignored.
2954 kif->kf_ref_count = -1;
2955 kif->kf_offset = -1;
2959 FILEDESC_SUNLOCK(fdp);
2960 vn_fullpath(curthread, vp, &fullpath, &freepath);
2961 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2963 VFS_UNLOCK_GIANT(vfslocked);
2964 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2965 if (freepath != NULL)
2966 free(freepath, M_TEMP);
2967 /* Pack record size down */
2968 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2969 strlen(kif->kf_path) + 1;
2970 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2971 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2972 FILEDESC_SLOCK(fdp);
2977 * Get per-process file descriptors for use by procstat(1), et al.
2980 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2982 char *fullpath, *freepath;
2983 struct kinfo_file *kif;
2984 struct filedesc *fdp;
2985 int error, i, *name;
2995 if ((p = pfind((pid_t)name[0])) == NULL)
2997 if ((error = p_candebug(curthread, p))) {
3005 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3006 FILEDESC_SLOCK(fdp);
3007 if (fdp->fd_cdir != NULL)
3008 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3010 if (fdp->fd_rdir != NULL)
3011 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3013 if (fdp->fd_jdir != NULL)
3014 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3016 for (i = 0; i < fdp->fd_nfiles; i++) {
3017 if ((fp = fdp->fd_ofiles[i]) == NULL)
3019 bzero(kif, sizeof(*kif));
3024 switch (fp->f_type) {
3026 kif->kf_type = KF_TYPE_VNODE;
3031 kif->kf_type = KF_TYPE_SOCKET;
3036 kif->kf_type = KF_TYPE_PIPE;
3040 kif->kf_type = KF_TYPE_FIFO;
3045 kif->kf_type = KF_TYPE_KQUEUE;
3049 kif->kf_type = KF_TYPE_CRYPTO;
3053 kif->kf_type = KF_TYPE_MQUEUE;
3057 kif->kf_type = KF_TYPE_SHM;
3061 kif->kf_type = KF_TYPE_SEM;
3065 kif->kf_type = KF_TYPE_PTS;
3070 kif->kf_type = KF_TYPE_UNKNOWN;
3073 kif->kf_ref_count = fp->f_count;
3074 if (fp->f_flag & FREAD)
3075 kif->kf_flags |= KF_FLAG_READ;
3076 if (fp->f_flag & FWRITE)
3077 kif->kf_flags |= KF_FLAG_WRITE;
3078 if (fp->f_flag & FAPPEND)
3079 kif->kf_flags |= KF_FLAG_APPEND;
3080 if (fp->f_flag & FASYNC)
3081 kif->kf_flags |= KF_FLAG_ASYNC;
3082 if (fp->f_flag & FFSYNC)
3083 kif->kf_flags |= KF_FLAG_FSYNC;
3084 if (fp->f_flag & FNONBLOCK)
3085 kif->kf_flags |= KF_FLAG_NONBLOCK;
3086 if (fp->f_flag & O_DIRECT)
3087 kif->kf_flags |= KF_FLAG_DIRECT;
3088 if (fp->f_flag & FHASLOCK)
3089 kif->kf_flags |= KF_FLAG_HASLOCK;
3090 kif->kf_offset = fp->f_offset;
3093 switch (vp->v_type) {
3095 kif->kf_vnode_type = KF_VTYPE_VNON;
3098 kif->kf_vnode_type = KF_VTYPE_VREG;
3101 kif->kf_vnode_type = KF_VTYPE_VDIR;
3104 kif->kf_vnode_type = KF_VTYPE_VBLK;
3107 kif->kf_vnode_type = KF_VTYPE_VCHR;
3110 kif->kf_vnode_type = KF_VTYPE_VLNK;
3113 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3116 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3119 kif->kf_vnode_type = KF_VTYPE_VBAD;
3122 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3126 * It is OK to drop the filedesc lock here as we will
3127 * re-validate and re-evaluate its properties when
3128 * the loop continues.
3132 FILEDESC_SUNLOCK(fdp);
3133 vn_fullpath(curthread, vp, &fullpath, &freepath);
3134 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3136 VFS_UNLOCK_GIANT(vfslocked);
3137 strlcpy(kif->kf_path, fullpath,
3138 sizeof(kif->kf_path));
3139 if (freepath != NULL)
3140 free(freepath, M_TEMP);
3141 FILEDESC_SLOCK(fdp);
3144 struct sockaddr *sa;
3146 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3147 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3148 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3151 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3152 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3153 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3156 kif->kf_sock_domain =
3157 so->so_proto->pr_domain->dom_family;
3158 kif->kf_sock_type = so->so_type;
3159 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3162 strlcpy(kif->kf_path, tty_devname(tp),
3163 sizeof(kif->kf_path));
3165 /* Pack record size down */
3166 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3167 strlen(kif->kf_path) + 1;
3168 kif->kf_structsize = roundup(kif->kf_structsize,
3170 oldidx = req->oldidx;
3171 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3173 if (error == ENOMEM) {
3175 * The hack to keep the ABI of sysctl
3176 * kern.proc.filedesc intact, but not
3177 * to account a partially copied
3178 * kinfo_file into the oldidx.
3180 req->oldidx = oldidx;
3186 FILEDESC_SUNLOCK(fdp);
3192 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3193 sysctl_kern_proc_filedesc, "Process filedesc entries");
3197 * For the purposes of debugging, generate a human-readable string for the
3201 file_type_to_name(short type)
3231 * For the purposes of debugging, identify a process (if any, perhaps one of
3232 * many) that references the passed file in its file descriptor array. Return
3235 static struct proc *
3236 file_to_first_proc(struct file *fp)
3238 struct filedesc *fdp;
3242 FOREACH_PROC_IN_SYSTEM(p) {
3243 if (p->p_state == PRS_NEW)
3248 for (n = 0; n < fdp->fd_nfiles; n++) {
3249 if (fp == fdp->fd_ofiles[n])
3257 db_print_file(struct file *fp, int header)
3262 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3263 "File", "Type", "Data", "Flag", "GCFl", "Count",
3264 "MCount", "Vnode", "FPID", "FCmd");
3265 p = file_to_first_proc(fp);
3266 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3267 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3268 0, fp->f_count, 0, fp->f_vnode,
3269 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3272 DB_SHOW_COMMAND(file, db_show_file)
3277 db_printf("usage: show file <addr>\n");
3280 fp = (struct file *)addr;
3281 db_print_file(fp, 1);
3284 DB_SHOW_COMMAND(files, db_show_files)
3286 struct filedesc *fdp;
3293 FOREACH_PROC_IN_SYSTEM(p) {
3294 if (p->p_state == PRS_NEW)
3296 if ((fdp = p->p_fd) == NULL)
3298 for (n = 0; n < fdp->fd_nfiles; ++n) {
3299 if ((fp = fdp->fd_ofiles[n]) == NULL)
3301 db_print_file(fp, header);
3308 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3309 &maxfilesperproc, 0, "Maximum files allowed open per process");
3311 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3312 &maxfiles, 0, "Maximum number of files");
3314 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3315 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3319 filelistinit(void *dummy)
3322 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3323 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3324 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3325 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3327 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3329 /*-------------------------------------------------------------------*/
3332 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3339 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3346 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3353 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3360 badfo_kqfilter(struct file *fp, struct knote *kn)
3367 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3374 badfo_close(struct file *fp, struct thread *td)
3380 struct fileops badfileops = {
3381 .fo_read = badfo_readwrite,
3382 .fo_write = badfo_readwrite,
3383 .fo_truncate = badfo_truncate,
3384 .fo_ioctl = badfo_ioctl,
3385 .fo_poll = badfo_poll,
3386 .fo_kqfilter = badfo_kqfilter,
3387 .fo_stat = badfo_stat,
3388 .fo_close = badfo_close,
3392 /*-------------------------------------------------------------------*/
3395 * File Descriptor pseudo-device driver (/dev/fd/).
3397 * Opening minor device N dup()s the file (if any) connected to file
3398 * descriptor N belonging to the calling process. Note that this driver
3399 * consists of only the ``open()'' routine, because all subsequent
3400 * references to this file will be direct to the other driver.
3402 * XXX: we could give this one a cloning event handler if necessary.
3407 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3411 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3412 * the file descriptor being sought for duplication. The error
3413 * return ensures that the vnode for this device will be released
3414 * by vn_open. Open will detect this special error and take the
3415 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3416 * will simply report the error.
3418 td->td_dupfd = dev2unit(dev);
3422 static struct cdevsw fildesc_cdevsw = {
3423 .d_version = D_VERSION,
3429 fildesc_drvinit(void *unused)
3433 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
3434 make_dev_alias(dev, "stdin");
3435 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
3436 make_dev_alias(dev, "stdout");
3437 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
3438 make_dev_alias(dev, "stderr");
3441 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);