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>
83 #include <security/audit/audit.h>
89 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
90 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
91 "file desc to leader structures");
92 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
94 MALLOC_DECLARE(M_FADVISE);
96 static uma_zone_t file_zone;
99 /* Flags for do_dup() */
100 #define DUP_FIXED 0x1 /* Force fixed allocation */
101 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
103 static int do_dup(struct thread *td, int flags, int old, int new,
105 static int fd_first_free(struct filedesc *, int, int);
106 static int fd_last_used(struct filedesc *, int, int);
107 static void fdgrowtable(struct filedesc *, int);
108 static void fdunused(struct filedesc *fdp, int fd);
109 static void fdused(struct filedesc *fdp, int fd);
112 * A process is initially started out with NDFILE descriptors stored within
113 * this structure, selected to be enough for typical applications based on
114 * the historical limit of 20 open files (and the usage of descriptors by
115 * shells). If these descriptors are exhausted, a larger descriptor table
116 * may be allocated, up to a process' resource limit; the internal arrays
120 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
121 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
122 #define NDSLOT(x) ((x) / NDENTRIES)
123 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
124 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
127 * Storage required per open file descriptor.
129 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
132 * Storage to hold unused ofiles that need to be reclaimed.
135 struct file **ft_table;
136 SLIST_ENTRY(freetable) ft_next;
140 * Basic allocation of descriptors:
141 * one of the above, plus arrays for NDFILE descriptors.
144 struct filedesc fd_fd;
146 * ofiles which need to be reclaimed on free.
148 SLIST_HEAD(,freetable) fd_free;
150 * These arrays are used when the number of open files is
151 * <= NDFILE, and are then pointed to by the pointers above.
153 struct file *fd_dfiles[NDFILE];
154 char fd_dfileflags[NDFILE];
155 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
159 * Descriptor management.
161 volatile int openfiles; /* actual number of open files */
162 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
163 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
165 /* A mutex to protect the association between a proc and filedesc. */
166 static struct mtx fdesc_mtx;
169 * Find the first zero bit in the given bitmap, starting at low and not
170 * exceeding size - 1.
173 fd_first_free(struct filedesc *fdp, int low, int size)
175 NDSLOTTYPE *map = fdp->fd_map;
183 if (low % NDENTRIES) {
184 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
185 if ((mask &= ~map[off]) != 0UL)
186 return (off * NDENTRIES + ffsl(mask) - 1);
189 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
190 if (map[off] != ~0UL)
191 return (off * NDENTRIES + ffsl(~map[off]) - 1);
196 * Find the highest non-zero bit in the given bitmap, starting at low and
197 * not exceeding size - 1.
200 fd_last_used(struct filedesc *fdp, int low, int size)
202 NDSLOTTYPE *map = fdp->fd_map;
210 if (size % NDENTRIES) {
211 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
212 if ((mask &= map[off]) != 0)
213 return (off * NDENTRIES + flsl(mask) - 1);
216 for (minoff = NDSLOT(low); off >= minoff; --off)
218 return (off * NDENTRIES + flsl(map[off]) - 1);
223 fdisused(struct filedesc *fdp, int fd)
225 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
226 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
227 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
231 * Mark a file descriptor as used.
234 fdused(struct filedesc *fdp, int fd)
237 FILEDESC_XLOCK_ASSERT(fdp);
238 KASSERT(!fdisused(fdp, fd),
239 ("fd already used"));
241 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
242 if (fd > fdp->fd_lastfile)
243 fdp->fd_lastfile = fd;
244 if (fd == fdp->fd_freefile)
245 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
249 * Mark a file descriptor as unused.
252 fdunused(struct filedesc *fdp, int fd)
255 FILEDESC_XLOCK_ASSERT(fdp);
256 KASSERT(fdisused(fdp, fd),
257 ("fd is already unused"));
258 KASSERT(fdp->fd_ofiles[fd] == NULL,
259 ("fd is still in use"));
261 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
262 if (fd < fdp->fd_freefile)
263 fdp->fd_freefile = fd;
264 if (fd == fdp->fd_lastfile)
265 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
269 * System calls on descriptors.
271 #ifndef _SYS_SYSPROTO_H_
272 struct getdtablesize_args {
278 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
280 struct proc *p = td->td_proc;
284 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
290 * Duplicate a file descriptor to a particular value.
292 * Note: keep in mind that a potential race condition exists when closing
293 * descriptors from a shared descriptor table (via rfork).
295 #ifndef _SYS_SYSPROTO_H_
303 dup2(struct thread *td, struct dup2_args *uap)
306 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
311 * Duplicate a file descriptor.
313 #ifndef _SYS_SYSPROTO_H_
320 dup(struct thread *td, struct dup_args *uap)
323 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
327 * The file control system call.
329 #ifndef _SYS_SYSPROTO_H_
338 fcntl(struct thread *td, struct fcntl_args *uap)
353 * Convert old flock structure to new.
355 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
356 fl.l_start = ofl.l_start;
357 fl.l_len = ofl.l_len;
358 fl.l_pid = ofl.l_pid;
359 fl.l_type = ofl.l_type;
360 fl.l_whence = ofl.l_whence;
380 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
389 error = kern_fcntl(td, uap->fd, cmd, arg);
392 if (uap->cmd == F_OGETLK) {
393 ofl.l_start = fl.l_start;
394 ofl.l_len = fl.l_len;
395 ofl.l_pid = fl.l_pid;
396 ofl.l_type = fl.l_type;
397 ofl.l_whence = fl.l_whence;
398 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
399 } else if (uap->cmd == F_GETLK) {
400 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
405 static inline struct file *
406 fdtofp(int fd, struct filedesc *fdp)
410 FILEDESC_LOCK_ASSERT(fdp);
411 if ((unsigned)fd >= fdp->fd_nfiles ||
412 (fp = fdp->fd_ofiles[fd]) == NULL)
418 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
420 struct filedesc *fdp;
440 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
445 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
450 if ((fp = fdtofp(fd, fdp)) == NULL) {
451 FILEDESC_SUNLOCK(fdp);
455 pop = &fdp->fd_ofileflags[fd];
456 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
457 FILEDESC_SUNLOCK(fdp);
462 if ((fp = fdtofp(fd, fdp)) == NULL) {
463 FILEDESC_XUNLOCK(fdp);
467 pop = &fdp->fd_ofileflags[fd];
468 *pop = (*pop &~ UF_EXCLOSE) |
469 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
470 FILEDESC_XUNLOCK(fdp);
475 if ((fp = fdtofp(fd, fdp)) == NULL) {
476 FILEDESC_SUNLOCK(fdp);
480 td->td_retval[0] = OFLAGS(fp->f_flag);
481 FILEDESC_SUNLOCK(fdp);
486 if ((fp = fdtofp(fd, fdp)) == NULL) {
487 FILEDESC_SUNLOCK(fdp);
492 FILEDESC_SUNLOCK(fdp);
494 tmp = flg = fp->f_flag;
496 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
497 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
498 tmp = fp->f_flag & FNONBLOCK;
499 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
504 tmp = fp->f_flag & FASYNC;
505 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
510 atomic_clear_int(&fp->f_flag, FNONBLOCK);
512 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
518 if ((fp = fdtofp(fd, fdp)) == NULL) {
519 FILEDESC_SUNLOCK(fdp);
524 FILEDESC_SUNLOCK(fdp);
525 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
527 td->td_retval[0] = tmp;
533 if ((fp = fdtofp(fd, fdp)) == NULL) {
534 FILEDESC_SUNLOCK(fdp);
539 FILEDESC_SUNLOCK(fdp);
541 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
546 error = priv_check(td, PRIV_NFS_LOCKD);
554 /* FALLTHROUGH F_SETLK */
559 if ((fp = fdtofp(fd, fdp)) == NULL) {
560 FILEDESC_SUNLOCK(fdp);
564 if (fp->f_type != DTYPE_VNODE) {
565 FILEDESC_SUNLOCK(fdp);
569 flp = (struct flock *)arg;
570 if (flp->l_whence == SEEK_CUR) {
571 if (fp->f_offset < 0 ||
573 fp->f_offset > OFF_MAX - flp->l_start)) {
574 FILEDESC_SUNLOCK(fdp);
578 flp->l_start += fp->f_offset;
582 * VOP_ADVLOCK() may block.
585 FILEDESC_SUNLOCK(fdp);
587 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
588 switch (flp->l_type) {
590 if ((fp->f_flag & FREAD) == 0) {
594 PROC_LOCK(p->p_leader);
595 p->p_leader->p_flag |= P_ADVLOCK;
596 PROC_UNLOCK(p->p_leader);
597 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
601 if ((fp->f_flag & FWRITE) == 0) {
605 PROC_LOCK(p->p_leader);
606 p->p_leader->p_flag |= P_ADVLOCK;
607 PROC_UNLOCK(p->p_leader);
608 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
612 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
617 * Temporary api for testing remote lock
620 if (flg != F_REMOTE) {
624 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
625 F_UNLCKSYS, flp, flg);
631 VFS_UNLOCK_GIANT(vfslocked);
633 /* Check for race with close */
635 if ((unsigned) fd >= fdp->fd_nfiles ||
636 fp != fdp->fd_ofiles[fd]) {
637 FILEDESC_SUNLOCK(fdp);
638 flp->l_whence = SEEK_SET;
641 flp->l_type = F_UNLCK;
642 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
643 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
644 F_UNLCK, flp, F_POSIX);
645 VFS_UNLOCK_GIANT(vfslocked);
648 FILEDESC_SUNLOCK(fdp);
654 if ((fp = fdtofp(fd, fdp)) == NULL) {
655 FILEDESC_SUNLOCK(fdp);
659 if (fp->f_type != DTYPE_VNODE) {
660 FILEDESC_SUNLOCK(fdp);
664 flp = (struct flock *)arg;
665 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
666 flp->l_type != F_UNLCK) {
667 FILEDESC_SUNLOCK(fdp);
671 if (flp->l_whence == SEEK_CUR) {
672 if ((flp->l_start > 0 &&
673 fp->f_offset > OFF_MAX - flp->l_start) ||
675 fp->f_offset < OFF_MIN - flp->l_start)) {
676 FILEDESC_SUNLOCK(fdp);
680 flp->l_start += fp->f_offset;
683 * VOP_ADVLOCK() may block.
686 FILEDESC_SUNLOCK(fdp);
688 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
689 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
691 VFS_UNLOCK_GIANT(vfslocked);
697 arg = arg ? 128 * 1024: 0;
701 if ((fp = fdtofp(fd, fdp)) == NULL) {
702 FILEDESC_SUNLOCK(fdp);
706 if (fp->f_type != DTYPE_VNODE) {
707 FILEDESC_SUNLOCK(fdp);
712 FILEDESC_SUNLOCK(fdp);
715 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
716 error = vn_lock(vp, LK_SHARED);
718 goto readahead_vnlock_fail;
719 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
721 fp->f_seqcount = (arg + bsize - 1) / bsize;
723 new = old = fp->f_flag;
725 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
726 readahead_vnlock_fail:
727 VFS_UNLOCK_GIANT(vfslocked);
731 new = old = fp->f_flag;
733 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
742 VFS_UNLOCK_GIANT(vfslocked);
747 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
750 do_dup(struct thread *td, int flags, int old, int new,
753 struct filedesc *fdp;
757 int error, holdleaders, maxfd;
763 * Verify we have a valid descriptor to dup from and possibly to
764 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
765 * return EINVAL when the new descriptor is out of bounds.
770 return (flags & DUP_FCNTL ? EINVAL : EBADF);
772 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
775 return (flags & DUP_FCNTL ? EINVAL : EMFILE);
778 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
779 FILEDESC_XUNLOCK(fdp);
782 if (flags & DUP_FIXED && old == new) {
784 FILEDESC_XUNLOCK(fdp);
787 fp = fdp->fd_ofiles[old];
791 * If the caller specified a file descriptor, make sure the file
792 * table is large enough to hold it, and grab it. Otherwise, just
793 * allocate a new descriptor the usual way. Since the filedesc
794 * lock may be temporarily dropped in the process, we have to look
797 if (flags & DUP_FIXED) {
798 if (new >= fdp->fd_nfiles)
799 fdgrowtable(fdp, new + 1);
800 if (fdp->fd_ofiles[new] == NULL)
803 if ((error = fdalloc(td, new, &new)) != 0) {
804 FILEDESC_XUNLOCK(fdp);
811 * If the old file changed out from under us then treat it as a
812 * bad file descriptor. Userland should do its own locking to
815 if (fdp->fd_ofiles[old] != fp) {
816 /* we've allocated a descriptor which we won't use */
817 if (fdp->fd_ofiles[new] == NULL)
819 FILEDESC_XUNLOCK(fdp);
824 ("new fd is same as old"));
827 * Save info on the descriptor being overwritten. We cannot close
828 * it without introducing an ownership race for the slot, since we
829 * need to drop the filedesc lock to call closef().
831 * XXX this duplicates parts of close().
833 delfp = fdp->fd_ofiles[new];
836 if (td->td_proc->p_fdtol != NULL) {
838 * Ask fdfree() to sleep to ensure that all relevant
839 * process leaders can be traversed in closef().
841 fdp->fd_holdleaderscount++;
847 * Duplicate the source descriptor
849 fdp->fd_ofiles[new] = fp;
850 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
851 if (new > fdp->fd_lastfile)
852 fdp->fd_lastfile = new;
856 * If we dup'd over a valid file, we now own the reference to it
857 * and must dispose of it using closef() semantics (as if a
858 * close() were performed on it).
860 * XXX this duplicates parts of close().
863 knote_fdclose(td, new);
864 if (delfp->f_type == DTYPE_MQUEUE)
865 mq_fdclose(td, new, delfp);
866 FILEDESC_XUNLOCK(fdp);
867 (void) closef(delfp, td);
870 fdp->fd_holdleaderscount--;
871 if (fdp->fd_holdleaderscount == 0 &&
872 fdp->fd_holdleaderswakeup != 0) {
873 fdp->fd_holdleaderswakeup = 0;
874 wakeup(&fdp->fd_holdleaderscount);
876 FILEDESC_XUNLOCK(fdp);
879 FILEDESC_XUNLOCK(fdp);
885 * If sigio is on the list associated with a process or process group,
886 * disable signalling from the device, remove sigio from the list and
890 funsetown(struct sigio **sigiop)
900 *(sigio->sio_myref) = NULL;
901 if ((sigio)->sio_pgid < 0) {
902 struct pgrp *pg = (sigio)->sio_pgrp;
904 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
908 struct proc *p = (sigio)->sio_proc;
910 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
915 crfree(sigio->sio_ucred);
916 free(sigio, M_SIGIO);
920 * Free a list of sigio structures.
921 * We only need to lock the SIGIO_LOCK because we have made ourselves
922 * inaccessible to callers of fsetown and therefore do not need to lock
923 * the proc or pgrp struct for the list manipulation.
926 funsetownlst(struct sigiolst *sigiolst)
932 sigio = SLIST_FIRST(sigiolst);
939 * Every entry of the list should belong
940 * to a single proc or pgrp.
942 if (sigio->sio_pgid < 0) {
943 pg = sigio->sio_pgrp;
944 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
945 } else /* if (sigio->sio_pgid > 0) */ {
947 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
951 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
952 *(sigio->sio_myref) = NULL;
954 KASSERT(sigio->sio_pgid < 0,
955 ("Proc sigio in pgrp sigio list"));
956 KASSERT(sigio->sio_pgrp == pg,
957 ("Bogus pgrp in sigio list"));
959 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
962 } else /* if (p != NULL) */ {
963 KASSERT(sigio->sio_pgid > 0,
964 ("Pgrp sigio in proc sigio list"));
965 KASSERT(sigio->sio_proc == p,
966 ("Bogus proc in sigio list"));
968 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
973 crfree(sigio->sio_ucred);
974 free(sigio, M_SIGIO);
981 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
983 * After permission checking, add a sigio structure to the sigio list for
984 * the process or process group.
987 fsetown(pid_t pgid, struct sigio **sigiop)
1001 /* Allocate and fill in the new sigio out of locks. */
1002 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1003 sigio->sio_pgid = pgid;
1004 sigio->sio_ucred = crhold(curthread->td_ucred);
1005 sigio->sio_myref = sigiop;
1007 sx_slock(&proctree_lock);
1016 * Policy - Don't allow a process to FSETOWN a process
1017 * in another session.
1019 * Remove this test to allow maximum flexibility or
1020 * restrict FSETOWN to the current process or process
1021 * group for maximum safety.
1024 if (proc->p_session != curthread->td_proc->p_session) {
1030 } else /* if (pgid < 0) */ {
1031 pgrp = pgfind(-pgid);
1039 * Policy - Don't allow a process to FSETOWN a process
1040 * in another session.
1042 * Remove this test to allow maximum flexibility or
1043 * restrict FSETOWN to the current process or process
1044 * group for maximum safety.
1046 if (pgrp->pg_session != curthread->td_proc->p_session) {
1057 * Since funsetownlst() is called without the proctree
1058 * locked, we need to check for P_WEXIT.
1059 * XXX: is ESRCH correct?
1061 if ((proc->p_flag & P_WEXIT) != 0) {
1066 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1067 sigio->sio_proc = proc;
1071 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1072 sigio->sio_pgrp = pgrp;
1075 sx_sunlock(&proctree_lock);
1082 sx_sunlock(&proctree_lock);
1083 crfree(sigio->sio_ucred);
1084 free(sigio, M_SIGIO);
1089 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1093 struct sigio **sigiop;
1098 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1104 * Close a file descriptor.
1106 #ifndef _SYS_SYSPROTO_H_
1115 struct close_args *uap;
1118 return (kern_close(td, uap->fd));
1126 struct filedesc *fdp;
1133 fdp = td->td_proc->p_fd;
1135 AUDIT_SYSCLOSE(td, fd);
1137 FILEDESC_XLOCK(fdp);
1138 if ((unsigned)fd >= fdp->fd_nfiles ||
1139 (fp = fdp->fd_ofiles[fd]) == NULL) {
1140 FILEDESC_XUNLOCK(fdp);
1143 fdp->fd_ofiles[fd] = NULL;
1144 fdp->fd_ofileflags[fd] = 0;
1146 if (td->td_proc->p_fdtol != NULL) {
1148 * Ask fdfree() to sleep to ensure that all relevant
1149 * process leaders can be traversed in closef().
1151 fdp->fd_holdleaderscount++;
1156 * We now hold the fp reference that used to be owned by the
1157 * descriptor array. We have to unlock the FILEDESC *AFTER*
1158 * knote_fdclose to prevent a race of the fd getting opened, a knote
1159 * added, and deleteing a knote for the new fd.
1161 knote_fdclose(td, fd);
1162 if (fp->f_type == DTYPE_MQUEUE)
1163 mq_fdclose(td, fd, fp);
1164 FILEDESC_XUNLOCK(fdp);
1166 error = closef(fp, td);
1168 FILEDESC_XLOCK(fdp);
1169 fdp->fd_holdleaderscount--;
1170 if (fdp->fd_holdleaderscount == 0 &&
1171 fdp->fd_holdleaderswakeup != 0) {
1172 fdp->fd_holdleaderswakeup = 0;
1173 wakeup(&fdp->fd_holdleaderscount);
1175 FILEDESC_XUNLOCK(fdp);
1181 * Close open file descriptors.
1183 #ifndef _SYS_SYSPROTO_H_
1184 struct closefrom_args {
1190 closefrom(struct thread *td, struct closefrom_args *uap)
1192 struct filedesc *fdp;
1195 fdp = td->td_proc->p_fd;
1196 AUDIT_ARG_FD(uap->lowfd);
1199 * Treat negative starting file descriptor values identical to
1200 * closefrom(0) which closes all files.
1204 FILEDESC_SLOCK(fdp);
1205 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1206 if (fdp->fd_ofiles[fd] != NULL) {
1207 FILEDESC_SUNLOCK(fdp);
1208 (void)kern_close(td, fd);
1209 FILEDESC_SLOCK(fdp);
1212 FILEDESC_SUNLOCK(fdp);
1216 #if defined(COMPAT_43)
1218 * Return status information about a file descriptor.
1220 #ifndef _SYS_SYSPROTO_H_
1221 struct ofstat_args {
1228 ofstat(struct thread *td, struct ofstat_args *uap)
1234 error = kern_fstat(td, uap->fd, &ub);
1237 error = copyout(&oub, uap->sb, sizeof(oub));
1241 #endif /* COMPAT_43 */
1244 * Return status information about a file descriptor.
1246 #ifndef _SYS_SYSPROTO_H_
1254 fstat(struct thread *td, struct fstat_args *uap)
1259 error = kern_fstat(td, uap->fd, &ub);
1261 error = copyout(&ub, uap->sb, sizeof(ub));
1266 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1273 if ((error = fget(td, fd, &fp)) != 0)
1276 AUDIT_ARG_FILE(td->td_proc, fp);
1278 error = fo_stat(fp, sbp, td->td_ucred, td);
1281 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1288 * Return status information about a file descriptor.
1290 #ifndef _SYS_SYSPROTO_H_
1291 struct nfstat_args {
1298 nfstat(struct thread *td, struct nfstat_args *uap)
1304 error = kern_fstat(td, uap->fd, &ub);
1306 cvtnstat(&ub, &nub);
1307 error = copyout(&nub, uap->sb, sizeof(nub));
1313 * Return pathconf information about a file descriptor.
1315 #ifndef _SYS_SYSPROTO_H_
1316 struct fpathconf_args {
1323 fpathconf(struct thread *td, struct fpathconf_args *uap)
1329 if ((error = fget(td, uap->fd, &fp)) != 0)
1332 /* If asynchronous I/O is available, it works for all descriptors. */
1333 if (uap->name == _PC_ASYNC_IO) {
1334 td->td_retval[0] = async_io_version;
1340 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1341 vn_lock(vp, LK_SHARED | LK_RETRY);
1342 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1344 VFS_UNLOCK_GIANT(vfslocked);
1345 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1346 if (uap->name != _PC_PIPE_BUF) {
1349 td->td_retval[0] = PIPE_BUF;
1361 * Grow the file table to accomodate (at least) nfd descriptors. This may
1362 * block and drop the filedesc lock, but it will reacquire it before
1366 fdgrowtable(struct filedesc *fdp, int nfd)
1368 struct filedesc0 *fdp0;
1369 struct freetable *fo;
1370 struct file **ntable;
1371 struct file **otable;
1373 int nnfiles, onfiles;
1376 FILEDESC_XLOCK_ASSERT(fdp);
1378 KASSERT(fdp->fd_nfiles > 0,
1379 ("zero-length file table"));
1381 /* compute the size of the new table */
1382 onfiles = fdp->fd_nfiles;
1383 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1384 if (nnfiles <= onfiles)
1385 /* the table is already large enough */
1388 /* allocate a new table and (if required) new bitmaps */
1389 FILEDESC_XUNLOCK(fdp);
1390 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1391 M_FILEDESC, M_ZERO | M_WAITOK);
1392 nfileflags = (char *)&ntable[nnfiles];
1393 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1394 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1395 M_FILEDESC, M_ZERO | M_WAITOK);
1398 FILEDESC_XLOCK(fdp);
1401 * We now have new tables ready to go. Since we dropped the
1402 * filedesc lock to call malloc(), watch out for a race.
1404 onfiles = fdp->fd_nfiles;
1405 if (onfiles >= nnfiles) {
1406 /* we lost the race, but that's OK */
1407 free(ntable, M_FILEDESC);
1409 free(nmap, M_FILEDESC);
1412 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1413 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1414 otable = fdp->fd_ofiles;
1415 fdp->fd_ofileflags = nfileflags;
1416 fdp->fd_ofiles = ntable;
1418 * We must preserve ofiles until the process exits because we can't
1419 * be certain that no threads have references to the old table via
1422 if (onfiles > NDFILE) {
1423 fo = (struct freetable *)&otable[onfiles];
1424 fdp0 = (struct filedesc0 *)fdp;
1425 fo->ft_table = otable;
1426 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1428 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1429 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1430 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1431 free(fdp->fd_map, M_FILEDESC);
1434 fdp->fd_nfiles = nnfiles;
1438 * Allocate a file descriptor for the process.
1441 fdalloc(struct thread *td, int minfd, int *result)
1443 struct proc *p = td->td_proc;
1444 struct filedesc *fdp = p->p_fd;
1447 FILEDESC_XLOCK_ASSERT(fdp);
1449 if (fdp->fd_freefile > minfd)
1450 minfd = fdp->fd_freefile;
1453 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1457 * Search the bitmap for a free descriptor. If none is found, try
1458 * to grow the file table. Keep at it until we either get a file
1459 * descriptor or run into process or system limits; fdgrowtable()
1460 * may drop the filedesc lock, so we're in a race.
1463 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1466 if (fd < fdp->fd_nfiles)
1468 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1472 * Perform some sanity checks, then mark the file descriptor as
1473 * used and return it to the caller.
1475 KASSERT(!fdisused(fdp, fd),
1476 ("fd_first_free() returned non-free descriptor"));
1477 KASSERT(fdp->fd_ofiles[fd] == NULL,
1478 ("free descriptor isn't"));
1479 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1486 * Check to see whether n user file descriptors are available to the process
1490 fdavail(struct thread *td, int n)
1492 struct proc *p = td->td_proc;
1493 struct filedesc *fdp = td->td_proc->p_fd;
1497 FILEDESC_LOCK_ASSERT(fdp);
1500 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1502 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1504 last = min(fdp->fd_nfiles, lim);
1505 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1506 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1507 if (*fpp == NULL && --n <= 0)
1514 * Create a new open file structure and allocate a file decriptor for the
1515 * process that refers to it. We add one reference to the file for the
1516 * descriptor table and one reference for resultfp. This is to prevent us
1517 * being preempted and the entry in the descriptor table closed after we
1518 * release the FILEDESC lock.
1521 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1523 struct proc *p = td->td_proc;
1526 int maxuserfiles = maxfiles - (maxfiles / 20);
1527 static struct timeval lastfail;
1530 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1531 if ((openfiles >= maxuserfiles &&
1532 priv_check(td, PRIV_MAXFILES) != 0) ||
1533 openfiles >= maxfiles) {
1534 if (ppsratecheck(&lastfail, &curfail, 1)) {
1535 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1536 td->td_ucred->cr_ruid);
1538 uma_zfree(file_zone, fp);
1541 atomic_add_int(&openfiles, 1);
1544 * If the process has file descriptor zero open, add the new file
1545 * descriptor to the list of open files at that point, otherwise
1546 * put it at the front of the list of open files.
1548 refcount_init(&fp->f_count, 1);
1551 fp->f_cred = crhold(td->td_ucred);
1552 fp->f_ops = &badfileops;
1555 FILEDESC_XLOCK(p->p_fd);
1556 if ((error = fdalloc(td, 0, &i))) {
1557 FILEDESC_XUNLOCK(p->p_fd);
1563 p->p_fd->fd_ofiles[i] = fp;
1564 if ((flags & O_CLOEXEC) != 0)
1565 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1566 FILEDESC_XUNLOCK(p->p_fd);
1575 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1578 return (fallocf(td, resultfp, resultfd, 0));
1582 * Build a new filedesc structure from another.
1583 * Copy the current, root, and jail root vnode references.
1586 fdinit(struct filedesc *fdp)
1588 struct filedesc0 *newfdp;
1590 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1591 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1593 FILEDESC_XLOCK(fdp);
1594 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1595 if (newfdp->fd_fd.fd_cdir)
1596 VREF(newfdp->fd_fd.fd_cdir);
1597 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1598 if (newfdp->fd_fd.fd_rdir)
1599 VREF(newfdp->fd_fd.fd_rdir);
1600 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1601 if (newfdp->fd_fd.fd_jdir)
1602 VREF(newfdp->fd_fd.fd_jdir);
1603 FILEDESC_XUNLOCK(fdp);
1606 /* Create the file descriptor table. */
1607 newfdp->fd_fd.fd_refcnt = 1;
1608 newfdp->fd_fd.fd_holdcnt = 1;
1609 newfdp->fd_fd.fd_cmask = CMASK;
1610 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1611 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1612 newfdp->fd_fd.fd_nfiles = NDFILE;
1613 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1614 newfdp->fd_fd.fd_lastfile = -1;
1615 return (&newfdp->fd_fd);
1618 static struct filedesc *
1619 fdhold(struct proc *p)
1621 struct filedesc *fdp;
1623 mtx_lock(&fdesc_mtx);
1627 mtx_unlock(&fdesc_mtx);
1632 fddrop(struct filedesc *fdp)
1634 struct filedesc0 *fdp0;
1635 struct freetable *ft;
1638 mtx_lock(&fdesc_mtx);
1639 i = --fdp->fd_holdcnt;
1640 mtx_unlock(&fdesc_mtx);
1644 FILEDESC_LOCK_DESTROY(fdp);
1645 fdp0 = (struct filedesc0 *)fdp;
1646 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1647 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1648 free(ft->ft_table, M_FILEDESC);
1650 free(fdp, M_FILEDESC);
1654 * Share a filedesc structure.
1657 fdshare(struct filedesc *fdp)
1660 FILEDESC_XLOCK(fdp);
1662 FILEDESC_XUNLOCK(fdp);
1667 * Unshare a filedesc structure, if necessary by making a copy
1670 fdunshare(struct proc *p, struct thread *td)
1673 FILEDESC_XLOCK(p->p_fd);
1674 if (p->p_fd->fd_refcnt > 1) {
1675 struct filedesc *tmp;
1677 FILEDESC_XUNLOCK(p->p_fd);
1678 tmp = fdcopy(p->p_fd);
1682 FILEDESC_XUNLOCK(p->p_fd);
1686 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1687 * this is to ease callers, not catch errors.
1690 fdcopy(struct filedesc *fdp)
1692 struct filedesc *newfdp;
1695 /* Certain daemons might not have file descriptors. */
1699 newfdp = fdinit(fdp);
1700 FILEDESC_SLOCK(fdp);
1701 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1702 FILEDESC_SUNLOCK(fdp);
1703 FILEDESC_XLOCK(newfdp);
1704 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1705 FILEDESC_XUNLOCK(newfdp);
1706 FILEDESC_SLOCK(fdp);
1708 /* copy everything except kqueue descriptors */
1709 newfdp->fd_freefile = -1;
1710 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1711 if (fdisused(fdp, i) &&
1712 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1713 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1714 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1715 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1716 fhold(newfdp->fd_ofiles[i]);
1717 newfdp->fd_lastfile = i;
1719 if (newfdp->fd_freefile == -1)
1720 newfdp->fd_freefile = i;
1723 newfdp->fd_cmask = fdp->fd_cmask;
1724 FILEDESC_SUNLOCK(fdp);
1725 FILEDESC_XLOCK(newfdp);
1726 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1727 if (newfdp->fd_ofiles[i] != NULL)
1729 if (newfdp->fd_freefile == -1)
1730 newfdp->fd_freefile = i;
1731 FILEDESC_XUNLOCK(newfdp);
1736 * Release a filedesc structure.
1739 fdfree(struct thread *td)
1741 struct filedesc *fdp;
1744 struct filedesc_to_leader *fdtol;
1746 struct vnode *cdir, *jdir, *rdir, *vp;
1749 /* Certain daemons might not have file descriptors. */
1750 fdp = td->td_proc->p_fd;
1754 /* Check for special need to clear POSIX style locks */
1755 fdtol = td->td_proc->p_fdtol;
1756 if (fdtol != NULL) {
1757 FILEDESC_XLOCK(fdp);
1758 KASSERT(fdtol->fdl_refcount > 0,
1759 ("filedesc_to_refcount botch: fdl_refcount=%d",
1760 fdtol->fdl_refcount));
1761 if (fdtol->fdl_refcount == 1 &&
1762 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1763 for (i = 0, fpp = fdp->fd_ofiles;
1764 i <= fdp->fd_lastfile;
1767 (*fpp)->f_type != DTYPE_VNODE)
1771 FILEDESC_XUNLOCK(fdp);
1772 lf.l_whence = SEEK_SET;
1775 lf.l_type = F_UNLCK;
1777 locked = VFS_LOCK_GIANT(vp->v_mount);
1778 (void) VOP_ADVLOCK(vp,
1779 (caddr_t)td->td_proc->
1784 VFS_UNLOCK_GIANT(locked);
1785 FILEDESC_XLOCK(fdp);
1787 fpp = fdp->fd_ofiles + i;
1791 if (fdtol->fdl_refcount == 1) {
1792 if (fdp->fd_holdleaderscount > 0 &&
1793 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1795 * close() or do_dup() has cleared a reference
1796 * in a shared file descriptor table.
1798 fdp->fd_holdleaderswakeup = 1;
1799 sx_sleep(&fdp->fd_holdleaderscount,
1800 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1803 if (fdtol->fdl_holdcount > 0) {
1805 * Ensure that fdtol->fdl_leader remains
1806 * valid in closef().
1808 fdtol->fdl_wakeup = 1;
1809 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1814 fdtol->fdl_refcount--;
1815 if (fdtol->fdl_refcount == 0 &&
1816 fdtol->fdl_holdcount == 0) {
1817 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1818 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1821 td->td_proc->p_fdtol = NULL;
1822 FILEDESC_XUNLOCK(fdp);
1824 free(fdtol, M_FILEDESC_TO_LEADER);
1826 FILEDESC_XLOCK(fdp);
1827 i = --fdp->fd_refcnt;
1828 FILEDESC_XUNLOCK(fdp);
1832 fpp = fdp->fd_ofiles;
1833 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1835 FILEDESC_XLOCK(fdp);
1838 FILEDESC_XUNLOCK(fdp);
1839 (void) closef(fp, td);
1842 FILEDESC_XLOCK(fdp);
1844 /* XXX This should happen earlier. */
1845 mtx_lock(&fdesc_mtx);
1846 td->td_proc->p_fd = NULL;
1847 mtx_unlock(&fdesc_mtx);
1849 if (fdp->fd_nfiles > NDFILE)
1850 free(fdp->fd_ofiles, M_FILEDESC);
1851 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1852 free(fdp->fd_map, M_FILEDESC);
1856 cdir = fdp->fd_cdir;
1857 fdp->fd_cdir = NULL;
1858 rdir = fdp->fd_rdir;
1859 fdp->fd_rdir = NULL;
1860 jdir = fdp->fd_jdir;
1861 fdp->fd_jdir = NULL;
1862 FILEDESC_XUNLOCK(fdp);
1865 locked = VFS_LOCK_GIANT(cdir->v_mount);
1867 VFS_UNLOCK_GIANT(locked);
1870 locked = VFS_LOCK_GIANT(rdir->v_mount);
1872 VFS_UNLOCK_GIANT(locked);
1875 locked = VFS_LOCK_GIANT(jdir->v_mount);
1877 VFS_UNLOCK_GIANT(locked);
1884 * For setugid programs, we don't want to people to use that setugidness
1885 * to generate error messages which write to a file which otherwise would
1886 * otherwise be off-limits to the process. We check for filesystems where
1887 * the vnode can change out from under us after execve (like [lin]procfs).
1889 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1890 * sufficient. We also don't check for setugidness since we know we are.
1893 is_unsafe(struct file *fp)
1895 if (fp->f_type == DTYPE_VNODE) {
1896 struct vnode *vp = fp->f_vnode;
1898 if ((vp->v_vflag & VV_PROCDEP) != 0)
1905 * Make this setguid thing safe, if at all possible.
1908 setugidsafety(struct thread *td)
1910 struct filedesc *fdp;
1913 /* Certain daemons might not have file descriptors. */
1914 fdp = td->td_proc->p_fd;
1919 * Note: fdp->fd_ofiles may be reallocated out from under us while
1920 * we are blocked in a close. Be careful!
1922 FILEDESC_XLOCK(fdp);
1923 for (i = 0; i <= fdp->fd_lastfile; i++) {
1926 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1929 knote_fdclose(td, i);
1931 * NULL-out descriptor prior to close to avoid
1932 * a race while close blocks.
1934 fp = fdp->fd_ofiles[i];
1935 fdp->fd_ofiles[i] = NULL;
1936 fdp->fd_ofileflags[i] = 0;
1938 FILEDESC_XUNLOCK(fdp);
1939 (void) closef(fp, td);
1940 FILEDESC_XLOCK(fdp);
1943 FILEDESC_XUNLOCK(fdp);
1947 * If a specific file object occupies a specific file descriptor, close the
1948 * file descriptor entry and drop a reference on the file object. This is a
1949 * convenience function to handle a subsequent error in a function that calls
1950 * falloc() that handles the race that another thread might have closed the
1951 * file descriptor out from under the thread creating the file object.
1954 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1957 FILEDESC_XLOCK(fdp);
1958 if (fdp->fd_ofiles[idx] == fp) {
1959 fdp->fd_ofiles[idx] = NULL;
1961 FILEDESC_XUNLOCK(fdp);
1964 FILEDESC_XUNLOCK(fdp);
1968 * Close any files on exec?
1971 fdcloseexec(struct thread *td)
1973 struct filedesc *fdp;
1976 /* Certain daemons might not have file descriptors. */
1977 fdp = td->td_proc->p_fd;
1981 FILEDESC_XLOCK(fdp);
1984 * We cannot cache fd_ofiles or fd_ofileflags since operations
1985 * may block and rip them out from under us.
1987 for (i = 0; i <= fdp->fd_lastfile; i++) {
1988 if (fdp->fd_ofiles[i] != NULL &&
1989 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1990 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1993 knote_fdclose(td, i);
1995 * NULL-out descriptor prior to close to avoid
1996 * a race while close blocks.
1998 fp = fdp->fd_ofiles[i];
1999 fdp->fd_ofiles[i] = NULL;
2000 fdp->fd_ofileflags[i] = 0;
2002 if (fp->f_type == DTYPE_MQUEUE)
2003 mq_fdclose(td, i, fp);
2004 FILEDESC_XUNLOCK(fdp);
2005 (void) closef(fp, td);
2006 FILEDESC_XLOCK(fdp);
2009 FILEDESC_XUNLOCK(fdp);
2013 * It is unsafe for set[ug]id processes to be started with file
2014 * descriptors 0..2 closed, as these descriptors are given implicit
2015 * significance in the Standard C library. fdcheckstd() will create a
2016 * descriptor referencing /dev/null for each of stdin, stdout, and
2017 * stderr that is not already open.
2020 fdcheckstd(struct thread *td)
2022 struct filedesc *fdp;
2023 register_t retval, save;
2024 int i, error, devnull;
2026 fdp = td->td_proc->p_fd;
2029 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2032 for (i = 0; i < 3; i++) {
2033 if (fdp->fd_ofiles[i] != NULL)
2036 save = td->td_retval[0];
2037 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2039 devnull = td->td_retval[0];
2040 td->td_retval[0] = save;
2043 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2045 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2054 * Internal form of close. Decrement reference count on file structure.
2055 * Note: td may be NULL when closing a file that was being passed in a
2058 * XXXRW: Giant is not required for the caller, but often will be held; this
2059 * makes it moderately likely the Giant will be recursed in the VFS case.
2062 closef(struct file *fp, struct thread *td)
2066 struct filedesc_to_leader *fdtol;
2067 struct filedesc *fdp;
2070 * POSIX record locking dictates that any close releases ALL
2071 * locks owned by this process. This is handled by setting
2072 * a flag in the unlock to free ONLY locks obeying POSIX
2073 * semantics, and not to free BSD-style file locks.
2074 * If the descriptor was in a message, POSIX-style locks
2075 * aren't passed with the descriptor, and the thread pointer
2076 * will be NULL. Callers should be careful only to pass a
2077 * NULL thread pointer when there really is no owning
2078 * context that might have locks, or the locks will be
2081 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2085 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2086 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2087 lf.l_whence = SEEK_SET;
2090 lf.l_type = F_UNLCK;
2091 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2092 F_UNLCK, &lf, F_POSIX);
2094 fdtol = td->td_proc->p_fdtol;
2095 if (fdtol != NULL) {
2097 * Handle special case where file descriptor table is
2098 * shared between multiple process leaders.
2100 fdp = td->td_proc->p_fd;
2101 FILEDESC_XLOCK(fdp);
2102 for (fdtol = fdtol->fdl_next;
2103 fdtol != td->td_proc->p_fdtol;
2104 fdtol = fdtol->fdl_next) {
2105 if ((fdtol->fdl_leader->p_flag &
2108 fdtol->fdl_holdcount++;
2109 FILEDESC_XUNLOCK(fdp);
2110 lf.l_whence = SEEK_SET;
2113 lf.l_type = F_UNLCK;
2115 (void) VOP_ADVLOCK(vp,
2116 (caddr_t)fdtol->fdl_leader,
2117 F_UNLCK, &lf, F_POSIX);
2118 FILEDESC_XLOCK(fdp);
2119 fdtol->fdl_holdcount--;
2120 if (fdtol->fdl_holdcount == 0 &&
2121 fdtol->fdl_wakeup != 0) {
2122 fdtol->fdl_wakeup = 0;
2126 FILEDESC_XUNLOCK(fdp);
2128 VFS_UNLOCK_GIANT(vfslocked);
2130 return (fdrop(fp, td));
2134 * Initialize the file pointer with the specified properties.
2136 * The ops are set with release semantics to be certain that the flags, type,
2137 * and data are visible when ops is. This is to prevent ops methods from being
2138 * called with bad data.
2141 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2146 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2150 fget_unlocked(struct filedesc *fdp, int fd)
2155 if (fd < 0 || fd >= fdp->fd_nfiles)
2158 * Fetch the descriptor locklessly. We avoid fdrop() races by
2159 * never raising a refcount above 0. To accomplish this we have
2160 * to use a cmpset loop rather than an atomic_add. The descriptor
2161 * must be re-verified once we acquire a reference to be certain
2162 * that the identity is still correct and we did not lose a race
2163 * due to preemption.
2166 fp = fdp->fd_ofiles[fd];
2169 count = fp->f_count;
2173 * Use an acquire barrier to prevent caching of fd_ofiles
2174 * so it is refreshed for verification.
2176 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2178 if (fp == fdp->fd_ofiles[fd])
2180 fdrop(fp, curthread);
2187 * Extract the file pointer associated with the specified descriptor for the
2188 * current user process.
2190 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2193 * If an error occured the non-zero error is returned and *fpp is set to
2194 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2195 * responsible for fdrop().
2198 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2200 struct filedesc *fdp;
2204 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2206 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2208 if (fp->f_ops == &badfileops) {
2213 * FREAD and FWRITE failure return EBADF as per POSIX.
2215 * Only one flag, or 0, may be specified.
2217 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2218 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2227 fget(struct thread *td, int fd, struct file **fpp)
2230 return(_fget(td, fd, fpp, 0));
2234 fget_read(struct thread *td, int fd, struct file **fpp)
2237 return(_fget(td, fd, fpp, FREAD));
2241 fget_write(struct thread *td, int fd, struct file **fpp)
2244 return(_fget(td, fd, fpp, FWRITE));
2248 * Like fget() but loads the underlying vnode, or returns an error if the
2249 * descriptor does not represent a vnode. Note that pipes use vnodes but
2250 * never have VM objects. The returned vnode will be vref()'d.
2252 * XXX: what about the unused flags ?
2255 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2261 if ((error = _fget(td, fd, &fp, flags)) != 0)
2263 if (fp->f_vnode == NULL) {
2275 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2278 return (_fgetvp(td, fd, vpp, 0));
2282 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2285 return (_fgetvp(td, fd, vpp, FREAD));
2290 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2293 return (_fgetvp(td, fd, vpp, FWRITE));
2298 * Like fget() but loads the underlying socket, or returns an error if the
2299 * descriptor does not represent a socket.
2301 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2304 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2305 * on their file descriptor reference to prevent the socket from being free'd
2309 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2317 if ((error = _fget(td, fd, &fp, 0)) != 0)
2319 if (fp->f_type != DTYPE_SOCKET) {
2324 *fflagp = fp->f_flag;
2335 * Drop the reference count on the socket and XXX release the SX lock in the
2336 * future. The last reference closes the socket.
2338 * Note: fputsock() is deprecated, see comment for fgetsock().
2341 fputsock(struct socket *so)
2346 CURVNET_SET(so->so_vnet);
2352 * Handle the last reference to a file being closed.
2355 _fdrop(struct file *fp, struct thread *td)
2360 if (fp->f_count != 0)
2361 panic("fdrop: count %d", fp->f_count);
2362 if (fp->f_ops != &badfileops)
2363 error = fo_close(fp, td);
2364 atomic_subtract_int(&openfiles, 1);
2366 free(fp->f_advice, M_FADVISE);
2367 uma_zfree(file_zone, fp);
2373 * Apply an advisory lock on a file descriptor.
2375 * Just attempt to get a record lock of the requested type on the entire file
2376 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2378 #ifndef _SYS_SYSPROTO_H_
2386 flock(struct thread *td, struct flock_args *uap)
2394 if ((error = fget(td, uap->fd, &fp)) != 0)
2396 if (fp->f_type != DTYPE_VNODE) {
2398 return (EOPNOTSUPP);
2402 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2403 lf.l_whence = SEEK_SET;
2406 if (uap->how & LOCK_UN) {
2407 lf.l_type = F_UNLCK;
2408 atomic_clear_int(&fp->f_flag, FHASLOCK);
2409 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2412 if (uap->how & LOCK_EX)
2413 lf.l_type = F_WRLCK;
2414 else if (uap->how & LOCK_SH)
2415 lf.l_type = F_RDLCK;
2420 atomic_set_int(&fp->f_flag, FHASLOCK);
2421 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2422 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2425 VFS_UNLOCK_GIANT(vfslocked);
2429 * Duplicate the specified descriptor to a free descriptor.
2432 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2438 * If the to-be-dup'd fd number is greater than the allowed number
2439 * of file descriptors, or the fd to be dup'd has already been
2440 * closed, then reject.
2442 FILEDESC_XLOCK(fdp);
2443 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2444 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2445 FILEDESC_XUNLOCK(fdp);
2450 * There are two cases of interest here.
2452 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2454 * For ENXIO steal away the file structure from (dfd) and store it in
2455 * (indx). (dfd) is effectively closed by this operation.
2457 * Any other error code is just returned.
2462 * Check that the mode the file is being opened for is a
2463 * subset of the mode of the existing descriptor.
2465 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2466 FILEDESC_XUNLOCK(fdp);
2469 fp = fdp->fd_ofiles[indx];
2470 fdp->fd_ofiles[indx] = wfp;
2471 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2475 FILEDESC_XUNLOCK(fdp);
2478 * We now own the reference to fp that the ofiles[]
2479 * array used to own. Release it.
2486 * Steal away the file pointer from dfd and stuff it into indx.
2488 fp = fdp->fd_ofiles[indx];
2489 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2490 fdp->fd_ofiles[dfd] = NULL;
2491 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2492 fdp->fd_ofileflags[dfd] = 0;
2496 FILEDESC_XUNLOCK(fdp);
2499 * We now own the reference to fp that the ofiles[] array
2500 * used to own. Release it.
2507 FILEDESC_XUNLOCK(fdp);
2514 * Scan all active processes and prisons to see if any of them have a current
2515 * or root directory of `olddp'. If so, replace them with the new mount point.
2518 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2520 struct filedesc *fdp;
2525 if (vrefcnt(olddp) == 1)
2528 sx_slock(&allproc_lock);
2529 FOREACH_PROC_IN_SYSTEM(p) {
2533 FILEDESC_XLOCK(fdp);
2534 if (fdp->fd_cdir == olddp) {
2536 fdp->fd_cdir = newdp;
2539 if (fdp->fd_rdir == olddp) {
2541 fdp->fd_rdir = newdp;
2544 if (fdp->fd_jdir == olddp) {
2546 fdp->fd_jdir = newdp;
2549 FILEDESC_XUNLOCK(fdp);
2552 sx_sunlock(&allproc_lock);
2553 if (rootvnode == olddp) {
2558 mtx_lock(&prison0.pr_mtx);
2559 if (prison0.pr_root == olddp) {
2561 prison0.pr_root = newdp;
2564 mtx_unlock(&prison0.pr_mtx);
2565 sx_slock(&allprison_lock);
2566 TAILQ_FOREACH(pr, &allprison, pr_list) {
2567 mtx_lock(&pr->pr_mtx);
2568 if (pr->pr_root == olddp) {
2570 pr->pr_root = newdp;
2573 mtx_unlock(&pr->pr_mtx);
2575 sx_sunlock(&allprison_lock);
2580 struct filedesc_to_leader *
2581 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2583 struct filedesc_to_leader *fdtol;
2585 fdtol = malloc(sizeof(struct filedesc_to_leader),
2586 M_FILEDESC_TO_LEADER,
2588 fdtol->fdl_refcount = 1;
2589 fdtol->fdl_holdcount = 0;
2590 fdtol->fdl_wakeup = 0;
2591 fdtol->fdl_leader = leader;
2593 FILEDESC_XLOCK(fdp);
2594 fdtol->fdl_next = old->fdl_next;
2595 fdtol->fdl_prev = old;
2596 old->fdl_next = fdtol;
2597 fdtol->fdl_next->fdl_prev = fdtol;
2598 FILEDESC_XUNLOCK(fdp);
2600 fdtol->fdl_next = fdtol;
2601 fdtol->fdl_prev = fdtol;
2607 * Get file structures globally.
2610 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2613 struct filedesc *fdp;
2618 error = sysctl_wire_old_buffer(req, 0);
2621 if (req->oldptr == NULL) {
2623 sx_slock(&allproc_lock);
2624 FOREACH_PROC_IN_SYSTEM(p) {
2625 if (p->p_state == PRS_NEW)
2630 /* overestimates sparse tables. */
2631 if (fdp->fd_lastfile > 0)
2632 n += fdp->fd_lastfile;
2635 sx_sunlock(&allproc_lock);
2636 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2639 bzero(&xf, sizeof(xf));
2640 xf.xf_size = sizeof(xf);
2641 sx_slock(&allproc_lock);
2642 FOREACH_PROC_IN_SYSTEM(p) {
2644 if (p->p_state == PRS_NEW) {
2648 if (p_cansee(req->td, p) != 0) {
2652 xf.xf_pid = p->p_pid;
2653 xf.xf_uid = p->p_ucred->cr_uid;
2658 FILEDESC_SLOCK(fdp);
2659 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2660 if ((fp = fdp->fd_ofiles[n]) == NULL)
2664 xf.xf_data = fp->f_data;
2665 xf.xf_vnode = fp->f_vnode;
2666 xf.xf_type = fp->f_type;
2667 xf.xf_count = fp->f_count;
2669 xf.xf_offset = fp->f_offset;
2670 xf.xf_flag = fp->f_flag;
2671 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2675 FILEDESC_SUNLOCK(fdp);
2680 sx_sunlock(&allproc_lock);
2684 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2685 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2687 #ifdef KINFO_OFILE_SIZE
2688 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2691 #ifdef COMPAT_FREEBSD7
2693 export_vnode_for_osysctl(struct vnode *vp, int type,
2694 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2697 char *fullpath, *freepath;
2700 bzero(kif, sizeof(*kif));
2701 kif->kf_structsize = sizeof(*kif);
2705 kif->kf_type = KF_TYPE_VNODE;
2706 /* This function only handles directories. */
2707 if (vp->v_type != VDIR) {
2711 kif->kf_vnode_type = KF_VTYPE_VDIR;
2714 * This is not a true file descriptor, so we set a bogus refcount
2715 * and offset to indicate these fields should be ignored.
2717 kif->kf_ref_count = -1;
2718 kif->kf_offset = -1;
2722 FILEDESC_SUNLOCK(fdp);
2723 vn_fullpath(curthread, vp, &fullpath, &freepath);
2724 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2726 VFS_UNLOCK_GIANT(vfslocked);
2727 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2728 if (freepath != NULL)
2729 free(freepath, M_TEMP);
2730 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2731 FILEDESC_SLOCK(fdp);
2736 * Get per-process file descriptors for use by procstat(1), et al.
2739 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2741 char *fullpath, *freepath;
2742 struct kinfo_ofile *kif;
2743 struct filedesc *fdp;
2744 int error, i, *name;
2753 if ((p = pfind((pid_t)name[0])) == NULL)
2755 if ((error = p_candebug(curthread, p))) {
2763 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2764 FILEDESC_SLOCK(fdp);
2765 if (fdp->fd_cdir != NULL)
2766 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2768 if (fdp->fd_rdir != NULL)
2769 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2771 if (fdp->fd_jdir != NULL)
2772 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2774 for (i = 0; i < fdp->fd_nfiles; i++) {
2775 if ((fp = fdp->fd_ofiles[i]) == NULL)
2777 bzero(kif, sizeof(*kif));
2778 kif->kf_structsize = sizeof(*kif);
2783 switch (fp->f_type) {
2785 kif->kf_type = KF_TYPE_VNODE;
2790 kif->kf_type = KF_TYPE_SOCKET;
2795 kif->kf_type = KF_TYPE_PIPE;
2799 kif->kf_type = KF_TYPE_FIFO;
2804 kif->kf_type = KF_TYPE_KQUEUE;
2808 kif->kf_type = KF_TYPE_CRYPTO;
2812 kif->kf_type = KF_TYPE_MQUEUE;
2816 kif->kf_type = KF_TYPE_SHM;
2820 kif->kf_type = KF_TYPE_SEM;
2824 kif->kf_type = KF_TYPE_PTS;
2829 kif->kf_type = KF_TYPE_UNKNOWN;
2832 kif->kf_ref_count = fp->f_count;
2833 if (fp->f_flag & FREAD)
2834 kif->kf_flags |= KF_FLAG_READ;
2835 if (fp->f_flag & FWRITE)
2836 kif->kf_flags |= KF_FLAG_WRITE;
2837 if (fp->f_flag & FAPPEND)
2838 kif->kf_flags |= KF_FLAG_APPEND;
2839 if (fp->f_flag & FASYNC)
2840 kif->kf_flags |= KF_FLAG_ASYNC;
2841 if (fp->f_flag & FFSYNC)
2842 kif->kf_flags |= KF_FLAG_FSYNC;
2843 if (fp->f_flag & FNONBLOCK)
2844 kif->kf_flags |= KF_FLAG_NONBLOCK;
2845 if (fp->f_flag & O_DIRECT)
2846 kif->kf_flags |= KF_FLAG_DIRECT;
2847 if (fp->f_flag & FHASLOCK)
2848 kif->kf_flags |= KF_FLAG_HASLOCK;
2849 kif->kf_offset = fp->f_offset;
2852 switch (vp->v_type) {
2854 kif->kf_vnode_type = KF_VTYPE_VNON;
2857 kif->kf_vnode_type = KF_VTYPE_VREG;
2860 kif->kf_vnode_type = KF_VTYPE_VDIR;
2863 kif->kf_vnode_type = KF_VTYPE_VBLK;
2866 kif->kf_vnode_type = KF_VTYPE_VCHR;
2869 kif->kf_vnode_type = KF_VTYPE_VLNK;
2872 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2875 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2878 kif->kf_vnode_type = KF_VTYPE_VBAD;
2881 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2885 * It is OK to drop the filedesc lock here as we will
2886 * re-validate and re-evaluate its properties when
2887 * the loop continues.
2891 FILEDESC_SUNLOCK(fdp);
2892 vn_fullpath(curthread, vp, &fullpath, &freepath);
2893 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2895 VFS_UNLOCK_GIANT(vfslocked);
2896 strlcpy(kif->kf_path, fullpath,
2897 sizeof(kif->kf_path));
2898 if (freepath != NULL)
2899 free(freepath, M_TEMP);
2900 FILEDESC_SLOCK(fdp);
2903 struct sockaddr *sa;
2905 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2906 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2907 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2910 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2911 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2912 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2915 kif->kf_sock_domain =
2916 so->so_proto->pr_domain->dom_family;
2917 kif->kf_sock_type = so->so_type;
2918 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2921 strlcpy(kif->kf_path, tty_devname(tp),
2922 sizeof(kif->kf_path));
2924 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2928 FILEDESC_SUNLOCK(fdp);
2934 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2935 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2936 #endif /* COMPAT_FREEBSD7 */
2938 #ifdef KINFO_FILE_SIZE
2939 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2943 export_vnode_for_sysctl(struct vnode *vp, int type,
2944 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2947 char *fullpath, *freepath;
2950 bzero(kif, sizeof(*kif));
2954 kif->kf_type = KF_TYPE_VNODE;
2955 /* This function only handles directories. */
2956 if (vp->v_type != VDIR) {
2960 kif->kf_vnode_type = KF_VTYPE_VDIR;
2963 * This is not a true file descriptor, so we set a bogus refcount
2964 * and offset to indicate these fields should be ignored.
2966 kif->kf_ref_count = -1;
2967 kif->kf_offset = -1;
2971 FILEDESC_SUNLOCK(fdp);
2972 vn_fullpath(curthread, vp, &fullpath, &freepath);
2973 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2975 VFS_UNLOCK_GIANT(vfslocked);
2976 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2977 if (freepath != NULL)
2978 free(freepath, M_TEMP);
2979 /* Pack record size down */
2980 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2981 strlen(kif->kf_path) + 1;
2982 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2983 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2984 FILEDESC_SLOCK(fdp);
2989 * Get per-process file descriptors for use by procstat(1), et al.
2992 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2994 char *fullpath, *freepath;
2995 struct kinfo_file *kif;
2996 struct filedesc *fdp;
2997 int error, i, *name;
3007 if ((p = pfind((pid_t)name[0])) == NULL)
3009 if ((error = p_candebug(curthread, p))) {
3017 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3018 FILEDESC_SLOCK(fdp);
3019 if (fdp->fd_cdir != NULL)
3020 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3022 if (fdp->fd_rdir != NULL)
3023 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3025 if (fdp->fd_jdir != NULL)
3026 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3028 for (i = 0; i < fdp->fd_nfiles; i++) {
3029 if ((fp = fdp->fd_ofiles[i]) == NULL)
3031 bzero(kif, sizeof(*kif));
3036 switch (fp->f_type) {
3038 kif->kf_type = KF_TYPE_VNODE;
3043 kif->kf_type = KF_TYPE_SOCKET;
3048 kif->kf_type = KF_TYPE_PIPE;
3052 kif->kf_type = KF_TYPE_FIFO;
3057 kif->kf_type = KF_TYPE_KQUEUE;
3061 kif->kf_type = KF_TYPE_CRYPTO;
3065 kif->kf_type = KF_TYPE_MQUEUE;
3069 kif->kf_type = KF_TYPE_SHM;
3073 kif->kf_type = KF_TYPE_SEM;
3077 kif->kf_type = KF_TYPE_PTS;
3082 kif->kf_type = KF_TYPE_UNKNOWN;
3085 kif->kf_ref_count = fp->f_count;
3086 if (fp->f_flag & FREAD)
3087 kif->kf_flags |= KF_FLAG_READ;
3088 if (fp->f_flag & FWRITE)
3089 kif->kf_flags |= KF_FLAG_WRITE;
3090 if (fp->f_flag & FAPPEND)
3091 kif->kf_flags |= KF_FLAG_APPEND;
3092 if (fp->f_flag & FASYNC)
3093 kif->kf_flags |= KF_FLAG_ASYNC;
3094 if (fp->f_flag & FFSYNC)
3095 kif->kf_flags |= KF_FLAG_FSYNC;
3096 if (fp->f_flag & FNONBLOCK)
3097 kif->kf_flags |= KF_FLAG_NONBLOCK;
3098 if (fp->f_flag & O_DIRECT)
3099 kif->kf_flags |= KF_FLAG_DIRECT;
3100 if (fp->f_flag & FHASLOCK)
3101 kif->kf_flags |= KF_FLAG_HASLOCK;
3102 kif->kf_offset = fp->f_offset;
3105 switch (vp->v_type) {
3107 kif->kf_vnode_type = KF_VTYPE_VNON;
3110 kif->kf_vnode_type = KF_VTYPE_VREG;
3113 kif->kf_vnode_type = KF_VTYPE_VDIR;
3116 kif->kf_vnode_type = KF_VTYPE_VBLK;
3119 kif->kf_vnode_type = KF_VTYPE_VCHR;
3122 kif->kf_vnode_type = KF_VTYPE_VLNK;
3125 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3128 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3131 kif->kf_vnode_type = KF_VTYPE_VBAD;
3134 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3138 * It is OK to drop the filedesc lock here as we will
3139 * re-validate and re-evaluate its properties when
3140 * the loop continues.
3144 FILEDESC_SUNLOCK(fdp);
3145 vn_fullpath(curthread, vp, &fullpath, &freepath);
3146 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3148 VFS_UNLOCK_GIANT(vfslocked);
3149 strlcpy(kif->kf_path, fullpath,
3150 sizeof(kif->kf_path));
3151 if (freepath != NULL)
3152 free(freepath, M_TEMP);
3153 FILEDESC_SLOCK(fdp);
3156 struct sockaddr *sa;
3158 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3159 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3160 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3163 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3164 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3165 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3168 kif->kf_sock_domain =
3169 so->so_proto->pr_domain->dom_family;
3170 kif->kf_sock_type = so->so_type;
3171 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3174 strlcpy(kif->kf_path, tty_devname(tp),
3175 sizeof(kif->kf_path));
3177 /* Pack record size down */
3178 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3179 strlen(kif->kf_path) + 1;
3180 kif->kf_structsize = roundup(kif->kf_structsize,
3182 oldidx = req->oldidx;
3183 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3185 if (error == ENOMEM) {
3187 * The hack to keep the ABI of sysctl
3188 * kern.proc.filedesc intact, but not
3189 * to account a partially copied
3190 * kinfo_file into the oldidx.
3192 req->oldidx = oldidx;
3198 FILEDESC_SUNLOCK(fdp);
3204 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3205 sysctl_kern_proc_filedesc, "Process filedesc entries");
3209 * For the purposes of debugging, generate a human-readable string for the
3213 file_type_to_name(short type)
3243 * For the purposes of debugging, identify a process (if any, perhaps one of
3244 * many) that references the passed file in its file descriptor array. Return
3247 static struct proc *
3248 file_to_first_proc(struct file *fp)
3250 struct filedesc *fdp;
3254 FOREACH_PROC_IN_SYSTEM(p) {
3255 if (p->p_state == PRS_NEW)
3260 for (n = 0; n < fdp->fd_nfiles; n++) {
3261 if (fp == fdp->fd_ofiles[n])
3269 db_print_file(struct file *fp, int header)
3274 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3275 "File", "Type", "Data", "Flag", "GCFl", "Count",
3276 "MCount", "Vnode", "FPID", "FCmd");
3277 p = file_to_first_proc(fp);
3278 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3279 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3280 0, fp->f_count, 0, fp->f_vnode,
3281 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3284 DB_SHOW_COMMAND(file, db_show_file)
3289 db_printf("usage: show file <addr>\n");
3292 fp = (struct file *)addr;
3293 db_print_file(fp, 1);
3296 DB_SHOW_COMMAND(files, db_show_files)
3298 struct filedesc *fdp;
3305 FOREACH_PROC_IN_SYSTEM(p) {
3306 if (p->p_state == PRS_NEW)
3308 if ((fdp = p->p_fd) == NULL)
3310 for (n = 0; n < fdp->fd_nfiles; ++n) {
3311 if ((fp = fdp->fd_ofiles[n]) == NULL)
3313 db_print_file(fp, header);
3320 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3321 &maxfilesperproc, 0, "Maximum files allowed open per process");
3323 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3324 &maxfiles, 0, "Maximum number of files");
3326 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3327 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3331 filelistinit(void *dummy)
3334 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3335 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3336 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3337 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3339 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3341 /*-------------------------------------------------------------------*/
3344 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3351 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3358 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3365 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3372 badfo_kqfilter(struct file *fp, struct knote *kn)
3379 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3386 badfo_close(struct file *fp, struct thread *td)
3392 struct fileops badfileops = {
3393 .fo_read = badfo_readwrite,
3394 .fo_write = badfo_readwrite,
3395 .fo_truncate = badfo_truncate,
3396 .fo_ioctl = badfo_ioctl,
3397 .fo_poll = badfo_poll,
3398 .fo_kqfilter = badfo_kqfilter,
3399 .fo_stat = badfo_stat,
3400 .fo_close = badfo_close,
3404 /*-------------------------------------------------------------------*/
3407 * File Descriptor pseudo-device driver (/dev/fd/).
3409 * Opening minor device N dup()s the file (if any) connected to file
3410 * descriptor N belonging to the calling process. Note that this driver
3411 * consists of only the ``open()'' routine, because all subsequent
3412 * references to this file will be direct to the other driver.
3414 * XXX: we could give this one a cloning event handler if necessary.
3419 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3423 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3424 * the file descriptor being sought for duplication. The error
3425 * return ensures that the vnode for this device will be released
3426 * by vn_open. Open will detect this special error and take the
3427 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3428 * will simply report the error.
3430 td->td_dupfd = dev2unit(dev);
3434 static struct cdevsw fildesc_cdevsw = {
3435 .d_version = D_VERSION,
3441 fildesc_drvinit(void *unused)
3445 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3446 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3447 make_dev_alias(dev, "stdin");
3448 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3449 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3450 make_dev_alias(dev, "stdout");
3451 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3452 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3453 make_dev_alias(dev, "stderr");
3456 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);