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_capsicum.h"
41 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44 #include "opt_procdesc.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capability.h>
51 #include <sys/domain.h>
52 #include <sys/fcntl.h>
54 #include <sys/filedesc.h>
55 #include <sys/filio.h>
57 #include <sys/kernel.h>
58 #include <sys/limits.h>
60 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mqueue.h>
64 #include <sys/mutex.h>
65 #include <sys/namei.h>
66 #include <sys/selinfo.h>
70 #include <sys/procdesc.h>
71 #include <sys/protosw.h>
72 #include <sys/racct.h>
73 #include <sys/resourcevar.h>
75 #include <sys/signalvar.h>
76 #include <sys/socketvar.h>
79 #include <sys/syscallsubr.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysproto.h>
83 #include <sys/unistd.h>
85 #include <sys/unpcb.h>
87 #include <sys/vnode.h>
89 #include <sys/ktrace.h>
94 #include <netinet/in.h>
95 #include <netinet/in_pcb.h>
97 #include <security/audit/audit.h>
104 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
105 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
106 "file desc to leader structures");
107 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
109 MALLOC_DECLARE(M_FADVISE);
111 static uma_zone_t file_zone;
114 /* Flags for do_dup() */
115 #define DUP_FIXED 0x1 /* Force fixed allocation */
116 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
117 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
119 static int do_dup(struct thread *td, int flags, int old, int new,
121 static int fd_first_free(struct filedesc *, int, int);
122 static int fd_last_used(struct filedesc *, int, int);
123 static void fdgrowtable(struct filedesc *, int);
124 static void fdunused(struct filedesc *fdp, int fd);
125 static void fdused(struct filedesc *fdp, int fd);
126 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
127 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
128 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
129 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
130 static int fill_procdesc_info(struct procdesc *pdp,
131 struct kinfo_file *kif);
132 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
135 * A process is initially started out with NDFILE descriptors stored within
136 * this structure, selected to be enough for typical applications based on
137 * the historical limit of 20 open files (and the usage of descriptors by
138 * shells). If these descriptors are exhausted, a larger descriptor table
139 * may be allocated, up to a process' resource limit; the internal arrays
143 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
144 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
145 #define NDSLOT(x) ((x) / NDENTRIES)
146 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
147 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
150 * Storage required per open file descriptor.
152 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
155 * Storage to hold unused ofiles that need to be reclaimed.
158 struct file **ft_table;
159 SLIST_ENTRY(freetable) ft_next;
163 * Basic allocation of descriptors:
164 * one of the above, plus arrays for NDFILE descriptors.
167 struct filedesc fd_fd;
169 * ofiles which need to be reclaimed on free.
171 SLIST_HEAD(,freetable) fd_free;
173 * These arrays are used when the number of open files is
174 * <= NDFILE, and are then pointed to by the pointers above.
176 struct file *fd_dfiles[NDFILE];
177 char fd_dfileflags[NDFILE];
178 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
182 * Descriptor management.
184 volatile int openfiles; /* actual number of open files */
185 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
186 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
188 /* A mutex to protect the association between a proc and filedesc. */
189 static struct mtx fdesc_mtx;
192 * Find the first zero bit in the given bitmap, starting at low and not
193 * exceeding size - 1.
196 fd_first_free(struct filedesc *fdp, int low, int size)
198 NDSLOTTYPE *map = fdp->fd_map;
206 if (low % NDENTRIES) {
207 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
208 if ((mask &= ~map[off]) != 0UL)
209 return (off * NDENTRIES + ffsl(mask) - 1);
212 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
213 if (map[off] != ~0UL)
214 return (off * NDENTRIES + ffsl(~map[off]) - 1);
219 * Find the highest non-zero bit in the given bitmap, starting at low and
220 * not exceeding size - 1.
223 fd_last_used(struct filedesc *fdp, int low, int size)
225 NDSLOTTYPE *map = fdp->fd_map;
233 if (size % NDENTRIES) {
234 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
235 if ((mask &= map[off]) != 0)
236 return (off * NDENTRIES + flsl(mask) - 1);
239 for (minoff = NDSLOT(low); off >= minoff; --off)
241 return (off * NDENTRIES + flsl(map[off]) - 1);
246 fdisused(struct filedesc *fdp, int fd)
248 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
249 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
250 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
254 * Mark a file descriptor as used.
257 fdused(struct filedesc *fdp, int fd)
260 FILEDESC_XLOCK_ASSERT(fdp);
261 KASSERT(!fdisused(fdp, fd),
262 ("fd already used"));
264 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
265 if (fd > fdp->fd_lastfile)
266 fdp->fd_lastfile = fd;
267 if (fd == fdp->fd_freefile)
268 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
272 * Mark a file descriptor as unused.
275 fdunused(struct filedesc *fdp, int fd)
278 FILEDESC_XLOCK_ASSERT(fdp);
279 KASSERT(fdisused(fdp, fd),
280 ("fd is already unused"));
281 KASSERT(fdp->fd_ofiles[fd] == NULL,
282 ("fd is still in use"));
284 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
285 if (fd < fdp->fd_freefile)
286 fdp->fd_freefile = fd;
287 if (fd == fdp->fd_lastfile)
288 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
292 * System calls on descriptors.
294 #ifndef _SYS_SYSPROTO_H_
295 struct getdtablesize_args {
301 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
303 struct proc *p = td->td_proc;
308 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
309 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
311 if (lim < td->td_retval[0])
312 td->td_retval[0] = lim;
317 * Duplicate a file descriptor to a particular value.
319 * Note: keep in mind that a potential race condition exists when closing
320 * descriptors from a shared descriptor table (via rfork).
322 #ifndef _SYS_SYSPROTO_H_
330 sys_dup2(struct thread *td, struct dup2_args *uap)
333 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
338 * Duplicate a file descriptor.
340 #ifndef _SYS_SYSPROTO_H_
347 sys_dup(struct thread *td, struct dup_args *uap)
350 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
354 * The file control system call.
356 #ifndef _SYS_SYSPROTO_H_
365 sys_fcntl(struct thread *td, struct fcntl_args *uap)
380 * Convert old flock structure to new.
382 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
383 fl.l_start = ofl.l_start;
384 fl.l_len = ofl.l_len;
385 fl.l_pid = ofl.l_pid;
386 fl.l_type = ofl.l_type;
387 fl.l_whence = ofl.l_whence;
407 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
416 error = kern_fcntl(td, uap->fd, cmd, arg);
419 if (uap->cmd == F_OGETLK) {
420 ofl.l_start = fl.l_start;
421 ofl.l_len = fl.l_len;
422 ofl.l_pid = fl.l_pid;
423 ofl.l_type = fl.l_type;
424 ofl.l_whence = fl.l_whence;
425 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
426 } else if (uap->cmd == F_GETLK) {
427 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
432 static inline struct file *
433 fdtofp(int fd, struct filedesc *fdp)
437 FILEDESC_LOCK_ASSERT(fdp);
438 if ((unsigned)fd >= fdp->fd_nfiles ||
439 (fp = fdp->fd_ofiles[fd]) == NULL)
445 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
448 *fpp = fdtofp(fd, fdp);
453 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
454 int err = cap_funwrap(*fpp, rights, fpp);
460 #endif /* CAPABILITIES */
465 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
467 struct filedesc *fdp;
488 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
491 case F_DUPFD_CLOEXEC:
493 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
499 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
502 case F_DUP2FD_CLOEXEC:
504 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
510 if ((fp = fdtofp(fd, fdp)) == NULL) {
511 FILEDESC_SUNLOCK(fdp);
515 pop = &fdp->fd_ofileflags[fd];
516 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
517 FILEDESC_SUNLOCK(fdp);
522 if ((fp = fdtofp(fd, fdp)) == NULL) {
523 FILEDESC_XUNLOCK(fdp);
527 pop = &fdp->fd_ofileflags[fd];
528 *pop = (*pop &~ UF_EXCLOSE) |
529 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
530 FILEDESC_XUNLOCK(fdp);
535 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
537 FILEDESC_SUNLOCK(fdp);
540 td->td_retval[0] = OFLAGS(fp->f_flag);
541 FILEDESC_SUNLOCK(fdp);
546 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
548 FILEDESC_SUNLOCK(fdp);
552 FILEDESC_SUNLOCK(fdp);
554 tmp = flg = fp->f_flag;
556 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
557 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
558 tmp = fp->f_flag & FNONBLOCK;
559 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
564 tmp = fp->f_flag & FASYNC;
565 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
570 atomic_clear_int(&fp->f_flag, FNONBLOCK);
572 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
578 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
580 FILEDESC_SUNLOCK(fdp);
584 FILEDESC_SUNLOCK(fdp);
585 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
587 td->td_retval[0] = tmp;
593 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
595 FILEDESC_SUNLOCK(fdp);
599 FILEDESC_SUNLOCK(fdp);
601 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
606 error = priv_check(td, PRIV_NFS_LOCKD);
614 /* FALLTHROUGH F_SETLK */
619 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
621 FILEDESC_SUNLOCK(fdp);
624 if (fp->f_type != DTYPE_VNODE) {
625 FILEDESC_SUNLOCK(fdp);
629 flp = (struct flock *)arg;
630 if (flp->l_whence == SEEK_CUR) {
631 foffset = foffset_get(fp);
634 foffset > OFF_MAX - flp->l_start)) {
635 FILEDESC_SUNLOCK(fdp);
639 flp->l_start += foffset;
643 * VOP_ADVLOCK() may block.
646 FILEDESC_SUNLOCK(fdp);
648 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
649 switch (flp->l_type) {
651 if ((fp->f_flag & FREAD) == 0) {
655 PROC_LOCK(p->p_leader);
656 p->p_leader->p_flag |= P_ADVLOCK;
657 PROC_UNLOCK(p->p_leader);
658 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
662 if ((fp->f_flag & FWRITE) == 0) {
666 PROC_LOCK(p->p_leader);
667 p->p_leader->p_flag |= P_ADVLOCK;
668 PROC_UNLOCK(p->p_leader);
669 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
673 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
678 * Temporary api for testing remote lock
681 if (flg != F_REMOTE) {
685 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
686 F_UNLCKSYS, flp, flg);
692 VFS_UNLOCK_GIANT(vfslocked);
694 /* Check for race with close */
696 if ((unsigned) fd >= fdp->fd_nfiles ||
697 fp != fdp->fd_ofiles[fd]) {
698 FILEDESC_SUNLOCK(fdp);
699 flp->l_whence = SEEK_SET;
702 flp->l_type = F_UNLCK;
703 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
704 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
705 F_UNLCK, flp, F_POSIX);
706 VFS_UNLOCK_GIANT(vfslocked);
709 FILEDESC_SUNLOCK(fdp);
715 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
717 FILEDESC_SUNLOCK(fdp);
720 if (fp->f_type != DTYPE_VNODE) {
721 FILEDESC_SUNLOCK(fdp);
725 flp = (struct flock *)arg;
726 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
727 flp->l_type != F_UNLCK) {
728 FILEDESC_SUNLOCK(fdp);
732 if (flp->l_whence == SEEK_CUR) {
733 foffset = foffset_get(fp);
734 if ((flp->l_start > 0 &&
735 foffset > OFF_MAX - flp->l_start) ||
737 foffset < OFF_MIN - flp->l_start)) {
738 FILEDESC_SUNLOCK(fdp);
742 flp->l_start += foffset;
745 * VOP_ADVLOCK() may block.
748 FILEDESC_SUNLOCK(fdp);
750 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
751 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
753 VFS_UNLOCK_GIANT(vfslocked);
759 arg = arg ? 128 * 1024: 0;
763 if ((fp = fdtofp(fd, fdp)) == NULL) {
764 FILEDESC_SUNLOCK(fdp);
768 if (fp->f_type != DTYPE_VNODE) {
769 FILEDESC_SUNLOCK(fdp);
774 FILEDESC_SUNLOCK(fdp);
777 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
778 error = vn_lock(vp, LK_SHARED);
780 goto readahead_vnlock_fail;
781 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
783 fp->f_seqcount = (arg + bsize - 1) / bsize;
785 new = old = fp->f_flag;
787 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
788 readahead_vnlock_fail:
789 VFS_UNLOCK_GIANT(vfslocked);
793 new = old = fp->f_flag;
795 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
804 VFS_UNLOCK_GIANT(vfslocked);
809 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
812 do_dup(struct thread *td, int flags, int old, int new,
815 struct filedesc *fdp;
819 int error, holdleaders, maxfd;
825 * Verify we have a valid descriptor to dup from and possibly to
826 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
827 * return EINVAL when the new descriptor is out of bounds.
832 return (flags & DUP_FCNTL ? EINVAL : EBADF);
834 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
837 return (flags & DUP_FCNTL ? EINVAL : EBADF);
840 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
841 FILEDESC_XUNLOCK(fdp);
844 if (flags & DUP_FIXED && old == new) {
846 if (flags & DUP_CLOEXEC)
847 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
848 FILEDESC_XUNLOCK(fdp);
851 fp = fdp->fd_ofiles[old];
855 * If the caller specified a file descriptor, make sure the file
856 * table is large enough to hold it, and grab it. Otherwise, just
857 * allocate a new descriptor the usual way. Since the filedesc
858 * lock may be temporarily dropped in the process, we have to look
861 if (flags & DUP_FIXED) {
862 if (new >= fdp->fd_nfiles) {
864 * The resource limits are here instead of e.g.
865 * fdalloc(), because the file descriptor table may be
866 * shared between processes, so we can't really use
867 * racct_add()/racct_sub(). Instead of counting the
868 * number of actually allocated descriptors, just put
869 * the limit on the size of the file descriptor table.
873 error = racct_set(p, RACCT_NOFILE, new + 1);
876 FILEDESC_XUNLOCK(fdp);
881 fdgrowtable(fdp, new + 1);
883 if (fdp->fd_ofiles[new] == NULL)
886 if ((error = fdalloc(td, new, &new)) != 0) {
887 FILEDESC_XUNLOCK(fdp);
894 * If the old file changed out from under us then treat it as a
895 * bad file descriptor. Userland should do its own locking to
898 if (fdp->fd_ofiles[old] != fp) {
899 /* we've allocated a descriptor which we won't use */
900 if (fdp->fd_ofiles[new] == NULL)
902 FILEDESC_XUNLOCK(fdp);
907 ("new fd is same as old"));
910 * Save info on the descriptor being overwritten. We cannot close
911 * it without introducing an ownership race for the slot, since we
912 * need to drop the filedesc lock to call closef().
914 * XXX this duplicates parts of close().
916 delfp = fdp->fd_ofiles[new];
919 if (td->td_proc->p_fdtol != NULL) {
921 * Ask fdfree() to sleep to ensure that all relevant
922 * process leaders can be traversed in closef().
924 fdp->fd_holdleaderscount++;
930 * Duplicate the source descriptor
932 fdp->fd_ofiles[new] = fp;
933 if ((flags & DUP_CLOEXEC) != 0)
934 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
936 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
937 if (new > fdp->fd_lastfile)
938 fdp->fd_lastfile = new;
942 * If we dup'd over a valid file, we now own the reference to it
943 * and must dispose of it using closef() semantics (as if a
944 * close() were performed on it).
946 * XXX this duplicates parts of close().
949 knote_fdclose(td, new);
950 if (delfp->f_type == DTYPE_MQUEUE)
951 mq_fdclose(td, new, delfp);
952 FILEDESC_XUNLOCK(fdp);
953 (void) closef(delfp, td);
956 fdp->fd_holdleaderscount--;
957 if (fdp->fd_holdleaderscount == 0 &&
958 fdp->fd_holdleaderswakeup != 0) {
959 fdp->fd_holdleaderswakeup = 0;
960 wakeup(&fdp->fd_holdleaderscount);
962 FILEDESC_XUNLOCK(fdp);
965 FILEDESC_XUNLOCK(fdp);
971 * If sigio is on the list associated with a process or process group,
972 * disable signalling from the device, remove sigio from the list and
976 funsetown(struct sigio **sigiop)
986 *(sigio->sio_myref) = NULL;
987 if ((sigio)->sio_pgid < 0) {
988 struct pgrp *pg = (sigio)->sio_pgrp;
990 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
994 struct proc *p = (sigio)->sio_proc;
996 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1001 crfree(sigio->sio_ucred);
1002 free(sigio, M_SIGIO);
1006 * Free a list of sigio structures.
1007 * We only need to lock the SIGIO_LOCK because we have made ourselves
1008 * inaccessible to callers of fsetown and therefore do not need to lock
1009 * the proc or pgrp struct for the list manipulation.
1012 funsetownlst(struct sigiolst *sigiolst)
1016 struct sigio *sigio;
1018 sigio = SLIST_FIRST(sigiolst);
1025 * Every entry of the list should belong
1026 * to a single proc or pgrp.
1028 if (sigio->sio_pgid < 0) {
1029 pg = sigio->sio_pgrp;
1030 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1031 } else /* if (sigio->sio_pgid > 0) */ {
1032 p = sigio->sio_proc;
1033 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1037 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1038 *(sigio->sio_myref) = NULL;
1040 KASSERT(sigio->sio_pgid < 0,
1041 ("Proc sigio in pgrp sigio list"));
1042 KASSERT(sigio->sio_pgrp == pg,
1043 ("Bogus pgrp in sigio list"));
1045 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1048 } else /* if (p != NULL) */ {
1049 KASSERT(sigio->sio_pgid > 0,
1050 ("Pgrp sigio in proc sigio list"));
1051 KASSERT(sigio->sio_proc == p,
1052 ("Bogus proc in sigio list"));
1054 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1059 crfree(sigio->sio_ucred);
1060 free(sigio, M_SIGIO);
1067 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1069 * After permission checking, add a sigio structure to the sigio list for
1070 * the process or process group.
1073 fsetown(pid_t pgid, struct sigio **sigiop)
1077 struct sigio *sigio;
1087 /* Allocate and fill in the new sigio out of locks. */
1088 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1089 sigio->sio_pgid = pgid;
1090 sigio->sio_ucred = crhold(curthread->td_ucred);
1091 sigio->sio_myref = sigiop;
1093 sx_slock(&proctree_lock);
1102 * Policy - Don't allow a process to FSETOWN a process
1103 * in another session.
1105 * Remove this test to allow maximum flexibility or
1106 * restrict FSETOWN to the current process or process
1107 * group for maximum safety.
1110 if (proc->p_session != curthread->td_proc->p_session) {
1116 } else /* if (pgid < 0) */ {
1117 pgrp = pgfind(-pgid);
1125 * Policy - Don't allow a process to FSETOWN a process
1126 * in another session.
1128 * Remove this test to allow maximum flexibility or
1129 * restrict FSETOWN to the current process or process
1130 * group for maximum safety.
1132 if (pgrp->pg_session != curthread->td_proc->p_session) {
1143 * Since funsetownlst() is called without the proctree
1144 * locked, we need to check for P_WEXIT.
1145 * XXX: is ESRCH correct?
1147 if ((proc->p_flag & P_WEXIT) != 0) {
1152 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1153 sigio->sio_proc = proc;
1157 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1158 sigio->sio_pgrp = pgrp;
1161 sx_sunlock(&proctree_lock);
1168 sx_sunlock(&proctree_lock);
1169 crfree(sigio->sio_ucred);
1170 free(sigio, M_SIGIO);
1175 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1179 struct sigio **sigiop;
1184 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1190 * Close a file descriptor.
1192 #ifndef _SYS_SYSPROTO_H_
1201 struct close_args *uap;
1204 return (kern_close(td, uap->fd));
1212 struct filedesc *fdp;
1213 struct file *fp, *fp_object;
1219 fdp = td->td_proc->p_fd;
1221 AUDIT_SYSCLOSE(td, fd);
1223 FILEDESC_XLOCK(fdp);
1224 if ((unsigned)fd >= fdp->fd_nfiles ||
1225 (fp = fdp->fd_ofiles[fd]) == NULL) {
1226 FILEDESC_XUNLOCK(fdp);
1229 fdp->fd_ofiles[fd] = NULL;
1230 fdp->fd_ofileflags[fd] = 0;
1232 if (td->td_proc->p_fdtol != NULL) {
1234 * Ask fdfree() to sleep to ensure that all relevant
1235 * process leaders can be traversed in closef().
1237 fdp->fd_holdleaderscount++;
1242 * We now hold the fp reference that used to be owned by the
1243 * descriptor array. We have to unlock the FILEDESC *AFTER*
1244 * knote_fdclose to prevent a race of the fd getting opened, a knote
1245 * added, and deleteing a knote for the new fd.
1247 knote_fdclose(td, fd);
1250 * When we're closing an fd with a capability, we need to notify
1251 * mqueue if the underlying object is of type mqueue.
1253 (void)cap_funwrap(fp, 0, &fp_object);
1254 if (fp_object->f_type == DTYPE_MQUEUE)
1255 mq_fdclose(td, fd, fp_object);
1256 FILEDESC_XUNLOCK(fdp);
1258 error = closef(fp, td);
1260 FILEDESC_XLOCK(fdp);
1261 fdp->fd_holdleaderscount--;
1262 if (fdp->fd_holdleaderscount == 0 &&
1263 fdp->fd_holdleaderswakeup != 0) {
1264 fdp->fd_holdleaderswakeup = 0;
1265 wakeup(&fdp->fd_holdleaderscount);
1267 FILEDESC_XUNLOCK(fdp);
1273 * Close open file descriptors.
1275 #ifndef _SYS_SYSPROTO_H_
1276 struct closefrom_args {
1282 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1284 struct filedesc *fdp;
1287 fdp = td->td_proc->p_fd;
1288 AUDIT_ARG_FD(uap->lowfd);
1291 * Treat negative starting file descriptor values identical to
1292 * closefrom(0) which closes all files.
1296 FILEDESC_SLOCK(fdp);
1297 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1298 if (fdp->fd_ofiles[fd] != NULL) {
1299 FILEDESC_SUNLOCK(fdp);
1300 (void)kern_close(td, fd);
1301 FILEDESC_SLOCK(fdp);
1304 FILEDESC_SUNLOCK(fdp);
1308 #if defined(COMPAT_43)
1310 * Return status information about a file descriptor.
1312 #ifndef _SYS_SYSPROTO_H_
1313 struct ofstat_args {
1320 ofstat(struct thread *td, struct ofstat_args *uap)
1326 error = kern_fstat(td, uap->fd, &ub);
1329 error = copyout(&oub, uap->sb, sizeof(oub));
1333 #endif /* COMPAT_43 */
1336 * Return status information about a file descriptor.
1338 #ifndef _SYS_SYSPROTO_H_
1346 sys_fstat(struct thread *td, struct fstat_args *uap)
1351 error = kern_fstat(td, uap->fd, &ub);
1353 error = copyout(&ub, uap->sb, sizeof(ub));
1358 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1365 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1368 AUDIT_ARG_FILE(td->td_proc, fp);
1370 error = fo_stat(fp, sbp, td->td_ucred, td);
1373 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1380 * Return status information about a file descriptor.
1382 #ifndef _SYS_SYSPROTO_H_
1383 struct nfstat_args {
1390 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1396 error = kern_fstat(td, uap->fd, &ub);
1398 cvtnstat(&ub, &nub);
1399 error = copyout(&nub, uap->sb, sizeof(nub));
1405 * Return pathconf information about a file descriptor.
1407 #ifndef _SYS_SYSPROTO_H_
1408 struct fpathconf_args {
1415 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1421 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1424 /* If asynchronous I/O is available, it works for all descriptors. */
1425 if (uap->name == _PC_ASYNC_IO) {
1426 td->td_retval[0] = async_io_version;
1432 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1433 vn_lock(vp, LK_SHARED | LK_RETRY);
1434 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1436 VFS_UNLOCK_GIANT(vfslocked);
1437 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1438 if (uap->name != _PC_PIPE_BUF) {
1441 td->td_retval[0] = PIPE_BUF;
1453 * Grow the file table to accomodate (at least) nfd descriptors. This may
1454 * block and drop the filedesc lock, but it will reacquire it before
1458 fdgrowtable(struct filedesc *fdp, int nfd)
1460 struct filedesc0 *fdp0;
1461 struct freetable *fo;
1462 struct file **ntable;
1463 struct file **otable;
1465 int nnfiles, onfiles;
1468 FILEDESC_XLOCK_ASSERT(fdp);
1470 KASSERT(fdp->fd_nfiles > 0,
1471 ("zero-length file table"));
1473 /* compute the size of the new table */
1474 onfiles = fdp->fd_nfiles;
1475 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1476 if (nnfiles <= onfiles)
1477 /* the table is already large enough */
1480 /* allocate a new table and (if required) new bitmaps */
1481 FILEDESC_XUNLOCK(fdp);
1482 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1483 M_FILEDESC, M_ZERO | M_WAITOK);
1484 nfileflags = (char *)&ntable[nnfiles];
1485 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1486 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1487 M_FILEDESC, M_ZERO | M_WAITOK);
1490 FILEDESC_XLOCK(fdp);
1493 * We now have new tables ready to go. Since we dropped the
1494 * filedesc lock to call malloc(), watch out for a race.
1496 onfiles = fdp->fd_nfiles;
1497 if (onfiles >= nnfiles) {
1498 /* we lost the race, but that's OK */
1499 free(ntable, M_FILEDESC);
1501 free(nmap, M_FILEDESC);
1504 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1505 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1506 otable = fdp->fd_ofiles;
1507 fdp->fd_ofileflags = nfileflags;
1508 fdp->fd_ofiles = ntable;
1510 * We must preserve ofiles until the process exits because we can't
1511 * be certain that no threads have references to the old table via
1514 if (onfiles > NDFILE) {
1515 fo = (struct freetable *)&otable[onfiles];
1516 fdp0 = (struct filedesc0 *)fdp;
1517 fo->ft_table = otable;
1518 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1520 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1521 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1522 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1523 free(fdp->fd_map, M_FILEDESC);
1526 fdp->fd_nfiles = nnfiles;
1530 * Allocate a file descriptor for the process.
1533 fdalloc(struct thread *td, int minfd, int *result)
1535 struct proc *p = td->td_proc;
1536 struct filedesc *fdp = p->p_fd;
1542 FILEDESC_XLOCK_ASSERT(fdp);
1544 if (fdp->fd_freefile > minfd)
1545 minfd = fdp->fd_freefile;
1548 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1552 * Search the bitmap for a free descriptor. If none is found, try
1553 * to grow the file table. Keep at it until we either get a file
1554 * descriptor or run into process or system limits; fdgrowtable()
1555 * may drop the filedesc lock, so we're in a race.
1558 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1561 if (fd < fdp->fd_nfiles)
1565 error = racct_set(p, RACCT_NOFILE, min(fdp->fd_nfiles * 2, maxfd));
1570 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1574 * Perform some sanity checks, then mark the file descriptor as
1575 * used and return it to the caller.
1577 KASSERT(!fdisused(fdp, fd),
1578 ("fd_first_free() returned non-free descriptor"));
1579 KASSERT(fdp->fd_ofiles[fd] == NULL,
1580 ("free descriptor isn't"));
1581 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1588 * Check to see whether n user file descriptors are available to the process
1592 fdavail(struct thread *td, int n)
1594 struct proc *p = td->td_proc;
1595 struct filedesc *fdp = td->td_proc->p_fd;
1599 FILEDESC_LOCK_ASSERT(fdp);
1602 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1603 * call racct_add() from there instead of dealing with containers
1607 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1609 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1611 last = min(fdp->fd_nfiles, lim);
1612 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1613 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1614 if (*fpp == NULL && --n <= 0)
1621 * Create a new open file structure and allocate a file decriptor for the
1622 * process that refers to it. We add one reference to the file for the
1623 * descriptor table and one reference for resultfp. This is to prevent us
1624 * being preempted and the entry in the descriptor table closed after we
1625 * release the FILEDESC lock.
1628 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1633 error = falloc_noinstall(td, &fp);
1635 return (error); /* no reference held on error */
1637 error = finstall(td, fp, &fd, flags);
1639 fdrop(fp, td); /* one reference (fp only) */
1643 if (resultfp != NULL)
1644 *resultfp = fp; /* copy out result */
1646 fdrop(fp, td); /* release local reference */
1648 if (resultfd != NULL)
1655 * Create a new open file structure without allocating a file descriptor.
1658 falloc_noinstall(struct thread *td, struct file **resultfp)
1661 int maxuserfiles = maxfiles - (maxfiles / 20);
1662 static struct timeval lastfail;
1665 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1667 if ((openfiles >= maxuserfiles &&
1668 priv_check(td, PRIV_MAXFILES) != 0) ||
1669 openfiles >= maxfiles) {
1670 if (ppsratecheck(&lastfail, &curfail, 1)) {
1671 printf("kern.maxfiles limit exceeded by uid %i, "
1672 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1676 atomic_add_int(&openfiles, 1);
1677 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1678 refcount_init(&fp->f_count, 1);
1679 fp->f_cred = crhold(td->td_ucred);
1680 fp->f_ops = &badfileops;
1688 * Install a file in a file descriptor table.
1691 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1693 struct filedesc *fdp = td->td_proc->p_fd;
1696 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1697 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1699 FILEDESC_XLOCK(fdp);
1700 if ((error = fdalloc(td, 0, fd))) {
1701 FILEDESC_XUNLOCK(fdp);
1705 fdp->fd_ofiles[*fd] = fp;
1706 if ((flags & O_CLOEXEC) != 0)
1707 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1708 FILEDESC_XUNLOCK(fdp);
1713 * Build a new filedesc structure from another.
1714 * Copy the current, root, and jail root vnode references.
1717 fdinit(struct filedesc *fdp)
1719 struct filedesc0 *newfdp;
1721 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1722 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1724 FILEDESC_XLOCK(fdp);
1725 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1726 if (newfdp->fd_fd.fd_cdir)
1727 VREF(newfdp->fd_fd.fd_cdir);
1728 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1729 if (newfdp->fd_fd.fd_rdir)
1730 VREF(newfdp->fd_fd.fd_rdir);
1731 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1732 if (newfdp->fd_fd.fd_jdir)
1733 VREF(newfdp->fd_fd.fd_jdir);
1734 FILEDESC_XUNLOCK(fdp);
1737 /* Create the file descriptor table. */
1738 newfdp->fd_fd.fd_refcnt = 1;
1739 newfdp->fd_fd.fd_holdcnt = 1;
1740 newfdp->fd_fd.fd_cmask = CMASK;
1741 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1742 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1743 newfdp->fd_fd.fd_nfiles = NDFILE;
1744 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1745 newfdp->fd_fd.fd_lastfile = -1;
1746 return (&newfdp->fd_fd);
1749 static struct filedesc *
1750 fdhold(struct proc *p)
1752 struct filedesc *fdp;
1754 mtx_lock(&fdesc_mtx);
1758 mtx_unlock(&fdesc_mtx);
1763 fddrop(struct filedesc *fdp)
1765 struct filedesc0 *fdp0;
1766 struct freetable *ft;
1769 mtx_lock(&fdesc_mtx);
1770 i = --fdp->fd_holdcnt;
1771 mtx_unlock(&fdesc_mtx);
1775 FILEDESC_LOCK_DESTROY(fdp);
1776 fdp0 = (struct filedesc0 *)fdp;
1777 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1778 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1779 free(ft->ft_table, M_FILEDESC);
1781 free(fdp, M_FILEDESC);
1785 * Share a filedesc structure.
1788 fdshare(struct filedesc *fdp)
1791 FILEDESC_XLOCK(fdp);
1793 FILEDESC_XUNLOCK(fdp);
1798 * Unshare a filedesc structure, if necessary by making a copy
1801 fdunshare(struct proc *p, struct thread *td)
1804 FILEDESC_XLOCK(p->p_fd);
1805 if (p->p_fd->fd_refcnt > 1) {
1806 struct filedesc *tmp;
1808 FILEDESC_XUNLOCK(p->p_fd);
1809 tmp = fdcopy(p->p_fd);
1813 FILEDESC_XUNLOCK(p->p_fd);
1817 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1818 * this is to ease callers, not catch errors.
1821 fdcopy(struct filedesc *fdp)
1823 struct filedesc *newfdp;
1826 /* Certain daemons might not have file descriptors. */
1830 newfdp = fdinit(fdp);
1831 FILEDESC_SLOCK(fdp);
1832 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1833 FILEDESC_SUNLOCK(fdp);
1834 FILEDESC_XLOCK(newfdp);
1835 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1836 FILEDESC_XUNLOCK(newfdp);
1837 FILEDESC_SLOCK(fdp);
1839 /* copy all passable descriptors (i.e. not kqueue) */
1840 newfdp->fd_freefile = -1;
1841 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1842 if (fdisused(fdp, i) &&
1843 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1844 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1845 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1846 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1847 fhold(newfdp->fd_ofiles[i]);
1848 newfdp->fd_lastfile = i;
1850 if (newfdp->fd_freefile == -1)
1851 newfdp->fd_freefile = i;
1854 newfdp->fd_cmask = fdp->fd_cmask;
1855 FILEDESC_SUNLOCK(fdp);
1856 FILEDESC_XLOCK(newfdp);
1857 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1858 if (newfdp->fd_ofiles[i] != NULL)
1860 if (newfdp->fd_freefile == -1)
1861 newfdp->fd_freefile = i;
1862 FILEDESC_XUNLOCK(newfdp);
1867 * Release a filedesc structure.
1870 fdfree(struct thread *td)
1872 struct filedesc *fdp;
1875 struct filedesc_to_leader *fdtol;
1877 struct vnode *cdir, *jdir, *rdir, *vp;
1880 /* Certain daemons might not have file descriptors. */
1881 fdp = td->td_proc->p_fd;
1886 PROC_LOCK(td->td_proc);
1887 racct_set(td->td_proc, RACCT_NOFILE, 0);
1888 PROC_UNLOCK(td->td_proc);
1891 /* Check for special need to clear POSIX style locks */
1892 fdtol = td->td_proc->p_fdtol;
1893 if (fdtol != NULL) {
1894 FILEDESC_XLOCK(fdp);
1895 KASSERT(fdtol->fdl_refcount > 0,
1896 ("filedesc_to_refcount botch: fdl_refcount=%d",
1897 fdtol->fdl_refcount));
1898 if (fdtol->fdl_refcount == 1 &&
1899 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1900 for (i = 0, fpp = fdp->fd_ofiles;
1901 i <= fdp->fd_lastfile;
1904 (*fpp)->f_type != DTYPE_VNODE)
1908 FILEDESC_XUNLOCK(fdp);
1909 lf.l_whence = SEEK_SET;
1912 lf.l_type = F_UNLCK;
1914 locked = VFS_LOCK_GIANT(vp->v_mount);
1915 (void) VOP_ADVLOCK(vp,
1916 (caddr_t)td->td_proc->
1921 VFS_UNLOCK_GIANT(locked);
1922 FILEDESC_XLOCK(fdp);
1924 fpp = fdp->fd_ofiles + i;
1928 if (fdtol->fdl_refcount == 1) {
1929 if (fdp->fd_holdleaderscount > 0 &&
1930 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1932 * close() or do_dup() has cleared a reference
1933 * in a shared file descriptor table.
1935 fdp->fd_holdleaderswakeup = 1;
1936 sx_sleep(&fdp->fd_holdleaderscount,
1937 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1940 if (fdtol->fdl_holdcount > 0) {
1942 * Ensure that fdtol->fdl_leader remains
1943 * valid in closef().
1945 fdtol->fdl_wakeup = 1;
1946 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1951 fdtol->fdl_refcount--;
1952 if (fdtol->fdl_refcount == 0 &&
1953 fdtol->fdl_holdcount == 0) {
1954 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1955 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1958 td->td_proc->p_fdtol = NULL;
1959 FILEDESC_XUNLOCK(fdp);
1961 free(fdtol, M_FILEDESC_TO_LEADER);
1963 FILEDESC_XLOCK(fdp);
1964 i = --fdp->fd_refcnt;
1965 FILEDESC_XUNLOCK(fdp);
1969 fpp = fdp->fd_ofiles;
1970 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1972 FILEDESC_XLOCK(fdp);
1975 FILEDESC_XUNLOCK(fdp);
1976 (void) closef(fp, td);
1979 FILEDESC_XLOCK(fdp);
1981 /* XXX This should happen earlier. */
1982 mtx_lock(&fdesc_mtx);
1983 td->td_proc->p_fd = NULL;
1984 mtx_unlock(&fdesc_mtx);
1986 if (fdp->fd_nfiles > NDFILE)
1987 free(fdp->fd_ofiles, M_FILEDESC);
1988 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1989 free(fdp->fd_map, M_FILEDESC);
1993 cdir = fdp->fd_cdir;
1994 fdp->fd_cdir = NULL;
1995 rdir = fdp->fd_rdir;
1996 fdp->fd_rdir = NULL;
1997 jdir = fdp->fd_jdir;
1998 fdp->fd_jdir = NULL;
1999 FILEDESC_XUNLOCK(fdp);
2002 locked = VFS_LOCK_GIANT(cdir->v_mount);
2004 VFS_UNLOCK_GIANT(locked);
2007 locked = VFS_LOCK_GIANT(rdir->v_mount);
2009 VFS_UNLOCK_GIANT(locked);
2012 locked = VFS_LOCK_GIANT(jdir->v_mount);
2014 VFS_UNLOCK_GIANT(locked);
2021 * For setugid programs, we don't want to people to use that setugidness
2022 * to generate error messages which write to a file which otherwise would
2023 * otherwise be off-limits to the process. We check for filesystems where
2024 * the vnode can change out from under us after execve (like [lin]procfs).
2026 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2027 * sufficient. We also don't check for setugidness since we know we are.
2030 is_unsafe(struct file *fp)
2032 if (fp->f_type == DTYPE_VNODE) {
2033 struct vnode *vp = fp->f_vnode;
2035 if ((vp->v_vflag & VV_PROCDEP) != 0)
2042 * Make this setguid thing safe, if at all possible.
2045 setugidsafety(struct thread *td)
2047 struct filedesc *fdp;
2050 /* Certain daemons might not have file descriptors. */
2051 fdp = td->td_proc->p_fd;
2056 * Note: fdp->fd_ofiles may be reallocated out from under us while
2057 * we are blocked in a close. Be careful!
2059 FILEDESC_XLOCK(fdp);
2060 for (i = 0; i <= fdp->fd_lastfile; i++) {
2063 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2066 knote_fdclose(td, i);
2068 * NULL-out descriptor prior to close to avoid
2069 * a race while close blocks.
2071 fp = fdp->fd_ofiles[i];
2072 fdp->fd_ofiles[i] = NULL;
2073 fdp->fd_ofileflags[i] = 0;
2075 FILEDESC_XUNLOCK(fdp);
2076 (void) closef(fp, td);
2077 FILEDESC_XLOCK(fdp);
2080 FILEDESC_XUNLOCK(fdp);
2084 * If a specific file object occupies a specific file descriptor, close the
2085 * file descriptor entry and drop a reference on the file object. This is a
2086 * convenience function to handle a subsequent error in a function that calls
2087 * falloc() that handles the race that another thread might have closed the
2088 * file descriptor out from under the thread creating the file object.
2091 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2094 FILEDESC_XLOCK(fdp);
2095 if (fdp->fd_ofiles[idx] == fp) {
2096 fdp->fd_ofiles[idx] = NULL;
2098 FILEDESC_XUNLOCK(fdp);
2101 FILEDESC_XUNLOCK(fdp);
2105 * Close any files on exec?
2108 fdcloseexec(struct thread *td)
2110 struct filedesc *fdp;
2113 /* Certain daemons might not have file descriptors. */
2114 fdp = td->td_proc->p_fd;
2118 FILEDESC_XLOCK(fdp);
2121 * We cannot cache fd_ofiles or fd_ofileflags since operations
2122 * may block and rip them out from under us.
2124 for (i = 0; i <= fdp->fd_lastfile; i++) {
2125 if (fdp->fd_ofiles[i] != NULL &&
2126 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2127 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2130 knote_fdclose(td, i);
2132 * NULL-out descriptor prior to close to avoid
2133 * a race while close blocks.
2135 fp = fdp->fd_ofiles[i];
2136 fdp->fd_ofiles[i] = NULL;
2137 fdp->fd_ofileflags[i] = 0;
2139 if (fp->f_type == DTYPE_MQUEUE)
2140 mq_fdclose(td, i, fp);
2141 FILEDESC_XUNLOCK(fdp);
2142 (void) closef(fp, td);
2143 FILEDESC_XLOCK(fdp);
2146 FILEDESC_XUNLOCK(fdp);
2150 * It is unsafe for set[ug]id processes to be started with file
2151 * descriptors 0..2 closed, as these descriptors are given implicit
2152 * significance in the Standard C library. fdcheckstd() will create a
2153 * descriptor referencing /dev/null for each of stdin, stdout, and
2154 * stderr that is not already open.
2157 fdcheckstd(struct thread *td)
2159 struct filedesc *fdp;
2160 register_t retval, save;
2161 int i, error, devnull;
2163 fdp = td->td_proc->p_fd;
2166 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2169 for (i = 0; i < 3; i++) {
2170 if (fdp->fd_ofiles[i] != NULL)
2173 save = td->td_retval[0];
2174 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2176 devnull = td->td_retval[0];
2177 td->td_retval[0] = save;
2180 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2182 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2191 * Internal form of close. Decrement reference count on file structure.
2192 * Note: td may be NULL when closing a file that was being passed in a
2195 * XXXRW: Giant is not required for the caller, but often will be held; this
2196 * makes it moderately likely the Giant will be recursed in the VFS case.
2199 closef(struct file *fp, struct thread *td)
2203 struct filedesc_to_leader *fdtol;
2204 struct filedesc *fdp;
2205 struct file *fp_object;
2208 * POSIX record locking dictates that any close releases ALL
2209 * locks owned by this process. This is handled by setting
2210 * a flag in the unlock to free ONLY locks obeying POSIX
2211 * semantics, and not to free BSD-style file locks.
2212 * If the descriptor was in a message, POSIX-style locks
2213 * aren't passed with the descriptor, and the thread pointer
2214 * will be NULL. Callers should be careful only to pass a
2215 * NULL thread pointer when there really is no owning
2216 * context that might have locks, or the locks will be
2219 * If this is a capability, we do lock processing under the underlying
2220 * node, not the capability itself.
2222 (void)cap_funwrap(fp, 0, &fp_object);
2223 if ((fp_object->f_type == DTYPE_VNODE) && (td != NULL)) {
2226 vp = fp_object->f_vnode;
2227 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2228 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2229 lf.l_whence = SEEK_SET;
2232 lf.l_type = F_UNLCK;
2233 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2234 F_UNLCK, &lf, F_POSIX);
2236 fdtol = td->td_proc->p_fdtol;
2237 if (fdtol != NULL) {
2239 * Handle special case where file descriptor table is
2240 * shared between multiple process leaders.
2242 fdp = td->td_proc->p_fd;
2243 FILEDESC_XLOCK(fdp);
2244 for (fdtol = fdtol->fdl_next;
2245 fdtol != td->td_proc->p_fdtol;
2246 fdtol = fdtol->fdl_next) {
2247 if ((fdtol->fdl_leader->p_flag &
2250 fdtol->fdl_holdcount++;
2251 FILEDESC_XUNLOCK(fdp);
2252 lf.l_whence = SEEK_SET;
2255 lf.l_type = F_UNLCK;
2256 vp = fp_object->f_vnode;
2257 (void) VOP_ADVLOCK(vp,
2258 (caddr_t)fdtol->fdl_leader,
2259 F_UNLCK, &lf, F_POSIX);
2260 FILEDESC_XLOCK(fdp);
2261 fdtol->fdl_holdcount--;
2262 if (fdtol->fdl_holdcount == 0 &&
2263 fdtol->fdl_wakeup != 0) {
2264 fdtol->fdl_wakeup = 0;
2268 FILEDESC_XUNLOCK(fdp);
2270 VFS_UNLOCK_GIANT(vfslocked);
2272 return (fdrop(fp, td));
2276 * Initialize the file pointer with the specified properties.
2278 * The ops are set with release semantics to be certain that the flags, type,
2279 * and data are visible when ops is. This is to prevent ops methods from being
2280 * called with bad data.
2283 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2288 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2292 fget_unlocked(struct filedesc *fdp, int fd)
2297 if (fd < 0 || fd >= fdp->fd_nfiles)
2300 * Fetch the descriptor locklessly. We avoid fdrop() races by
2301 * never raising a refcount above 0. To accomplish this we have
2302 * to use a cmpset loop rather than an atomic_add. The descriptor
2303 * must be re-verified once we acquire a reference to be certain
2304 * that the identity is still correct and we did not lose a race
2305 * due to preemption.
2308 fp = fdp->fd_ofiles[fd];
2311 count = fp->f_count;
2315 * Use an acquire barrier to prevent caching of fd_ofiles
2316 * so it is refreshed for verification.
2318 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2320 if (fp == fdp->fd_ofiles[fd])
2322 fdrop(fp, curthread);
2329 * Extract the file pointer associated with the specified descriptor for the
2330 * current user process.
2332 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2335 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2336 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2337 * Otherwise, if the file is a capability, its rights will be checked against
2338 * the capability rights mask, and if successful, the object will be unwrapped.
2340 * If an error occured the non-zero error is returned and *fpp is set to
2341 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2342 * responsible for fdrop().
2344 #define FGET_GETCAP 0x00000001
2346 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2347 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2350 struct filedesc *fdp;
2353 struct file *fp_fromcap;
2358 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2360 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2362 if (fp->f_ops == &badfileops) {
2369 * If this is a capability, what rights does it have?
2371 if (haverightsp != NULL) {
2372 if (fp->f_type == DTYPE_CAPABILITY)
2373 *haverightsp = cap_rights(fp);
2375 *haverightsp = CAP_MASK_VALID;
2379 * If a capability has been requested, return the capability directly.
2380 * Otherwise, check capability rights, extract the underlying object,
2381 * and check its access flags.
2383 if (fget_flags & FGET_GETCAP) {
2384 if (fp->f_type != DTYPE_CAPABILITY) {
2389 if (maxprotp == NULL)
2390 error = cap_funwrap(fp, needrights, &fp_fromcap);
2392 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2400 * If we've unwrapped a file, drop the original capability
2401 * and hold the new descriptor. fp after this point refers to
2402 * the actual (unwrapped) object, not the capability.
2404 if (fp != fp_fromcap) {
2410 #else /* !CAPABILITIES */
2411 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2412 ("%s: saw capability", __func__));
2413 if (maxprotp != NULL)
2414 *maxprotp = VM_PROT_ALL;
2415 #endif /* CAPABILITIES */
2418 * FREAD and FWRITE failure return EBADF as per POSIX.
2424 if ((fp->f_flag & flags) == 0)
2428 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2429 ((fp->f_flag & FWRITE) != 0))
2435 KASSERT(0, ("wrong flags"));
2448 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2451 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2455 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2459 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2463 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2466 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2470 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2473 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2477 * Unlike the other fget() calls, which accept and check capability rights
2478 * but never return capabilities, fgetcap() returns the capability but doesn't
2479 * check capability rights.
2482 fgetcap(struct thread *td, int fd, struct file **fpp)
2485 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2490 * Like fget() but loads the underlying vnode, or returns an error if the
2491 * descriptor does not represent a vnode. Note that pipes use vnodes but
2492 * never have VM objects. The returned vnode will be vref()'d.
2494 * XXX: what about the unused flags ?
2497 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2498 cap_rights_t *haverightsp, struct vnode **vpp)
2504 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2507 if (fp->f_vnode == NULL) {
2519 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2522 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2526 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2529 return (_fgetvp(td, fd, 0, need, have, vpp));
2533 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2536 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2540 fgetvp_exec(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2543 return (_fgetvp(td, fd, FEXEC, rights, NULL, vpp));
2548 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2552 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2557 * Like fget() but loads the underlying socket, or returns an error if the
2558 * descriptor does not represent a socket.
2560 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2563 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2564 * on their file descriptor reference to prevent the socket from being free'd
2568 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2577 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2579 if (fp->f_type != DTYPE_SOCKET) {
2584 *fflagp = fp->f_flag;
2595 * Drop the reference count on the socket and XXX release the SX lock in the
2596 * future. The last reference closes the socket.
2598 * Note: fputsock() is deprecated, see comment for fgetsock().
2601 fputsock(struct socket *so)
2606 CURVNET_SET(so->so_vnet);
2612 * Handle the last reference to a file being closed.
2614 * No special capability handling here, as the capability's fo_close will run
2615 * instead of the object here, and perform any necessary drop on the object.
2618 _fdrop(struct file *fp, struct thread *td)
2623 if (fp->f_count != 0)
2624 panic("fdrop: count %d", fp->f_count);
2625 if (fp->f_ops != &badfileops)
2626 error = fo_close(fp, td);
2627 atomic_subtract_int(&openfiles, 1);
2629 free(fp->f_advice, M_FADVISE);
2630 uma_zfree(file_zone, fp);
2636 * Apply an advisory lock on a file descriptor.
2638 * Just attempt to get a record lock of the requested type on the entire file
2639 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2641 #ifndef _SYS_SYSPROTO_H_
2649 sys_flock(struct thread *td, struct flock_args *uap)
2657 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2659 if (fp->f_type != DTYPE_VNODE) {
2661 return (EOPNOTSUPP);
2665 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2666 lf.l_whence = SEEK_SET;
2669 if (uap->how & LOCK_UN) {
2670 lf.l_type = F_UNLCK;
2671 atomic_clear_int(&fp->f_flag, FHASLOCK);
2672 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2675 if (uap->how & LOCK_EX)
2676 lf.l_type = F_WRLCK;
2677 else if (uap->how & LOCK_SH)
2678 lf.l_type = F_RDLCK;
2683 atomic_set_int(&fp->f_flag, FHASLOCK);
2684 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2685 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2688 VFS_UNLOCK_GIANT(vfslocked);
2692 * Duplicate the specified descriptor to a free descriptor.
2695 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2701 * If the to-be-dup'd fd number is greater than the allowed number
2702 * of file descriptors, or the fd to be dup'd has already been
2703 * closed, then reject.
2705 FILEDESC_XLOCK(fdp);
2706 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2707 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2708 FILEDESC_XUNLOCK(fdp);
2713 * There are two cases of interest here.
2715 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2717 * For ENXIO steal away the file structure from (dfd) and store it in
2718 * (indx). (dfd) is effectively closed by this operation.
2720 * Any other error code is just returned.
2725 * Check that the mode the file is being opened for is a
2726 * subset of the mode of the existing descriptor.
2728 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2729 FILEDESC_XUNLOCK(fdp);
2732 fp = fdp->fd_ofiles[indx];
2733 fdp->fd_ofiles[indx] = wfp;
2734 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2738 FILEDESC_XUNLOCK(fdp);
2741 * We now own the reference to fp that the ofiles[]
2742 * array used to own. Release it.
2749 * Steal away the file pointer from dfd and stuff it into indx.
2751 fp = fdp->fd_ofiles[indx];
2752 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2753 fdp->fd_ofiles[dfd] = NULL;
2754 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2755 fdp->fd_ofileflags[dfd] = 0;
2759 FILEDESC_XUNLOCK(fdp);
2762 * We now own the reference to fp that the ofiles[] array
2763 * used to own. Release it.
2770 FILEDESC_XUNLOCK(fdp);
2777 * Scan all active processes and prisons to see if any of them have a current
2778 * or root directory of `olddp'. If so, replace them with the new mount point.
2781 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2783 struct filedesc *fdp;
2788 if (vrefcnt(olddp) == 1)
2791 sx_slock(&allproc_lock);
2792 FOREACH_PROC_IN_SYSTEM(p) {
2796 FILEDESC_XLOCK(fdp);
2797 if (fdp->fd_cdir == olddp) {
2799 fdp->fd_cdir = newdp;
2802 if (fdp->fd_rdir == olddp) {
2804 fdp->fd_rdir = newdp;
2807 if (fdp->fd_jdir == olddp) {
2809 fdp->fd_jdir = newdp;
2812 FILEDESC_XUNLOCK(fdp);
2815 sx_sunlock(&allproc_lock);
2816 if (rootvnode == olddp) {
2821 mtx_lock(&prison0.pr_mtx);
2822 if (prison0.pr_root == olddp) {
2824 prison0.pr_root = newdp;
2827 mtx_unlock(&prison0.pr_mtx);
2828 sx_slock(&allprison_lock);
2829 TAILQ_FOREACH(pr, &allprison, pr_list) {
2830 mtx_lock(&pr->pr_mtx);
2831 if (pr->pr_root == olddp) {
2833 pr->pr_root = newdp;
2836 mtx_unlock(&pr->pr_mtx);
2838 sx_sunlock(&allprison_lock);
2843 struct filedesc_to_leader *
2844 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2846 struct filedesc_to_leader *fdtol;
2848 fdtol = malloc(sizeof(struct filedesc_to_leader),
2849 M_FILEDESC_TO_LEADER,
2851 fdtol->fdl_refcount = 1;
2852 fdtol->fdl_holdcount = 0;
2853 fdtol->fdl_wakeup = 0;
2854 fdtol->fdl_leader = leader;
2856 FILEDESC_XLOCK(fdp);
2857 fdtol->fdl_next = old->fdl_next;
2858 fdtol->fdl_prev = old;
2859 old->fdl_next = fdtol;
2860 fdtol->fdl_next->fdl_prev = fdtol;
2861 FILEDESC_XUNLOCK(fdp);
2863 fdtol->fdl_next = fdtol;
2864 fdtol->fdl_prev = fdtol;
2870 * Get file structures globally.
2873 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2876 struct filedesc *fdp;
2881 error = sysctl_wire_old_buffer(req, 0);
2884 if (req->oldptr == NULL) {
2886 sx_slock(&allproc_lock);
2887 FOREACH_PROC_IN_SYSTEM(p) {
2888 if (p->p_state == PRS_NEW)
2893 /* overestimates sparse tables. */
2894 if (fdp->fd_lastfile > 0)
2895 n += fdp->fd_lastfile;
2898 sx_sunlock(&allproc_lock);
2899 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2902 bzero(&xf, sizeof(xf));
2903 xf.xf_size = sizeof(xf);
2904 sx_slock(&allproc_lock);
2905 FOREACH_PROC_IN_SYSTEM(p) {
2907 if (p->p_state == PRS_NEW) {
2911 if (p_cansee(req->td, p) != 0) {
2915 xf.xf_pid = p->p_pid;
2916 xf.xf_uid = p->p_ucred->cr_uid;
2921 FILEDESC_SLOCK(fdp);
2922 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2923 if ((fp = fdp->fd_ofiles[n]) == NULL)
2927 xf.xf_data = fp->f_data;
2928 xf.xf_vnode = fp->f_vnode;
2929 xf.xf_type = fp->f_type;
2930 xf.xf_count = fp->f_count;
2932 xf.xf_offset = foffset_get(fp);
2933 xf.xf_flag = fp->f_flag;
2934 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2938 FILEDESC_SUNLOCK(fdp);
2943 sx_sunlock(&allproc_lock);
2947 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2948 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2950 #ifdef KINFO_OFILE_SIZE
2951 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2954 #ifdef COMPAT_FREEBSD7
2956 export_vnode_for_osysctl(struct vnode *vp, int type,
2957 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2960 char *fullpath, *freepath;
2963 bzero(kif, sizeof(*kif));
2964 kif->kf_structsize = sizeof(*kif);
2968 kif->kf_type = KF_TYPE_VNODE;
2969 /* This function only handles directories. */
2970 if (vp->v_type != VDIR) {
2974 kif->kf_vnode_type = KF_VTYPE_VDIR;
2977 * This is not a true file descriptor, so we set a bogus refcount
2978 * and offset to indicate these fields should be ignored.
2980 kif->kf_ref_count = -1;
2981 kif->kf_offset = -1;
2985 FILEDESC_SUNLOCK(fdp);
2986 vn_fullpath(curthread, vp, &fullpath, &freepath);
2987 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2989 VFS_UNLOCK_GIANT(vfslocked);
2990 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2991 if (freepath != NULL)
2992 free(freepath, M_TEMP);
2993 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2994 FILEDESC_SLOCK(fdp);
2999 * Get per-process file descriptors for use by procstat(1), et al.
3002 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3004 char *fullpath, *freepath;
3005 struct kinfo_ofile *kif;
3006 struct filedesc *fdp;
3007 int error, i, *name;
3008 struct shmfd *shmfd;
3017 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3024 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3025 FILEDESC_SLOCK(fdp);
3026 if (fdp->fd_cdir != NULL)
3027 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3029 if (fdp->fd_rdir != NULL)
3030 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3032 if (fdp->fd_jdir != NULL)
3033 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3035 for (i = 0; i < fdp->fd_nfiles; i++) {
3036 if ((fp = fdp->fd_ofiles[i]) == NULL)
3038 bzero(kif, sizeof(*kif));
3039 kif->kf_structsize = sizeof(*kif);
3048 * When reporting a capability, most fields will be from the
3049 * underlying object, but do mark as a capability. With
3050 * ofiledesc, we don't have a field to export the cap_rights_t,
3051 * but we do with the new filedesc.
3053 if (fp->f_type == DTYPE_CAPABILITY) {
3054 kif->kf_flags |= KF_FLAG_CAPABILITY;
3055 (void)cap_funwrap(fp, 0, &fp);
3058 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3059 ("sysctl_kern_proc_ofiledesc: saw capability"));
3061 switch (fp->f_type) {
3063 kif->kf_type = KF_TYPE_VNODE;
3068 kif->kf_type = KF_TYPE_SOCKET;
3073 kif->kf_type = KF_TYPE_PIPE;
3077 kif->kf_type = KF_TYPE_FIFO;
3082 kif->kf_type = KF_TYPE_KQUEUE;
3086 kif->kf_type = KF_TYPE_CRYPTO;
3090 kif->kf_type = KF_TYPE_MQUEUE;
3094 kif->kf_type = KF_TYPE_SHM;
3099 kif->kf_type = KF_TYPE_SEM;
3103 kif->kf_type = KF_TYPE_PTS;
3108 case DTYPE_PROCDESC:
3109 kif->kf_type = KF_TYPE_PROCDESC;
3114 kif->kf_type = KF_TYPE_UNKNOWN;
3117 kif->kf_ref_count = fp->f_count;
3118 if (fp->f_flag & FREAD)
3119 kif->kf_flags |= KF_FLAG_READ;
3120 if (fp->f_flag & FWRITE)
3121 kif->kf_flags |= KF_FLAG_WRITE;
3122 if (fp->f_flag & FAPPEND)
3123 kif->kf_flags |= KF_FLAG_APPEND;
3124 if (fp->f_flag & FASYNC)
3125 kif->kf_flags |= KF_FLAG_ASYNC;
3126 if (fp->f_flag & FFSYNC)
3127 kif->kf_flags |= KF_FLAG_FSYNC;
3128 if (fp->f_flag & FNONBLOCK)
3129 kif->kf_flags |= KF_FLAG_NONBLOCK;
3130 if (fp->f_flag & O_DIRECT)
3131 kif->kf_flags |= KF_FLAG_DIRECT;
3132 if (fp->f_flag & FHASLOCK)
3133 kif->kf_flags |= KF_FLAG_HASLOCK;
3134 kif->kf_offset = foffset_get(fp);
3137 switch (vp->v_type) {
3139 kif->kf_vnode_type = KF_VTYPE_VNON;
3142 kif->kf_vnode_type = KF_VTYPE_VREG;
3145 kif->kf_vnode_type = KF_VTYPE_VDIR;
3148 kif->kf_vnode_type = KF_VTYPE_VBLK;
3151 kif->kf_vnode_type = KF_VTYPE_VCHR;
3154 kif->kf_vnode_type = KF_VTYPE_VLNK;
3157 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3160 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3163 kif->kf_vnode_type = KF_VTYPE_VBAD;
3166 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3170 * It is OK to drop the filedesc lock here as we will
3171 * re-validate and re-evaluate its properties when
3172 * the loop continues.
3176 FILEDESC_SUNLOCK(fdp);
3177 vn_fullpath(curthread, vp, &fullpath, &freepath);
3178 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3180 VFS_UNLOCK_GIANT(vfslocked);
3181 strlcpy(kif->kf_path, fullpath,
3182 sizeof(kif->kf_path));
3183 if (freepath != NULL)
3184 free(freepath, M_TEMP);
3185 FILEDESC_SLOCK(fdp);
3188 struct sockaddr *sa;
3190 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3191 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3192 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3195 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3196 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3197 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3200 kif->kf_sock_domain =
3201 so->so_proto->pr_domain->dom_family;
3202 kif->kf_sock_type = so->so_type;
3203 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3206 strlcpy(kif->kf_path, tty_devname(tp),
3207 sizeof(kif->kf_path));
3210 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3211 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3215 FILEDESC_SUNLOCK(fdp);
3221 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3222 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3223 #endif /* COMPAT_FREEBSD7 */
3225 #ifdef KINFO_FILE_SIZE
3226 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3230 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3231 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3232 struct kinfo_file *kif, struct sbuf *sb, ssize_t *remainder)
3237 } fflags_table[] = {
3238 { FAPPEND, KF_FLAG_APPEND },
3239 { FASYNC, KF_FLAG_ASYNC },
3240 { FFSYNC, KF_FLAG_FSYNC },
3241 { FHASLOCK, KF_FLAG_HASLOCK },
3242 { FNONBLOCK, KF_FLAG_NONBLOCK },
3243 { FREAD, KF_FLAG_READ },
3244 { FWRITE, KF_FLAG_WRITE },
3245 { O_CREAT, KF_FLAG_CREAT },
3246 { O_DIRECT, KF_FLAG_DIRECT },
3247 { O_EXCL, KF_FLAG_EXCL },
3248 { O_EXEC, KF_FLAG_EXEC },
3249 { O_EXLOCK, KF_FLAG_EXLOCK },
3250 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3251 { O_SHLOCK, KF_FLAG_SHLOCK },
3252 { O_TRUNC, KF_FLAG_TRUNC }
3254 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3256 int error, vfslocked;
3259 if (*remainder == 0)
3261 bzero(kif, sizeof(*kif));
3265 vp = (struct vnode *)data;
3266 error = fill_vnode_info(vp, kif);
3267 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3269 VFS_UNLOCK_GIANT(vfslocked);
3271 case KF_TYPE_SOCKET:
3272 error = fill_socket_info((struct socket *)data, kif);
3275 error = fill_pipe_info((struct pipe *)data, kif);
3278 error = fill_pts_info((struct tty *)data, kif);
3280 case KF_TYPE_PROCDESC:
3281 error = fill_procdesc_info((struct procdesc *)data, kif);
3284 error = fill_shm_info((struct file *)data, kif);
3290 kif->kf_status |= KF_ATTR_VALID;
3293 * Translate file access flags.
3295 for (i = 0; i < NFFLAGS; i++)
3296 if (fflags & fflags_table[i].fflag)
3297 kif->kf_flags |= fflags_table[i].kf_fflag;
3299 kif->kf_flags |= KF_FLAG_CAPABILITY;
3301 kif->kf_cap_rights = fd_cap_rights;
3303 kif->kf_type = type;
3304 kif->kf_ref_count = refcnt;
3305 kif->kf_offset = offset;
3306 /* Pack record size down */
3307 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3308 strlen(kif->kf_path) + 1;
3309 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3310 if (*remainder != -1) {
3311 if (*remainder < kif->kf_structsize) {
3312 /* Terminate export. */
3316 *remainder -= kif->kf_structsize;
3318 error = sbuf_bcat(sb, kif, kif->kf_structsize);
3323 * Store a process file descriptor information to sbuf.
3325 * Takes a locked proc as argument, and returns with the proc unlocked.
3328 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3331 struct filedesc *fdp;
3332 struct kinfo_file *kif;
3333 struct vnode *cttyvp, *textvp, *tracevp;
3338 int fd_is_cap, type, refcnt, fflags;
3339 cap_rights_t fd_cap_rights;
3341 PROC_LOCK_ASSERT(p, MA_OWNED);
3345 tracevp = p->p_tracevp;
3346 if (tracevp != NULL)
3349 textvp = p->p_textvp;
3352 /* Controlling tty. */
3354 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3355 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3361 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3362 if (tracevp != NULL)
3363 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3364 FREAD | FWRITE, -1, -1, 0, 0, kif, sb, &remainder);
3366 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3367 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3369 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3370 FREAD | FWRITE, -1, -1, 0, 0, kif, sb, &remainder);
3374 FILEDESC_SLOCK(fdp);
3375 /* working directory */
3376 if (fdp->fd_cdir != NULL) {
3378 data = fdp->fd_cdir;
3379 FILEDESC_SUNLOCK(fdp);
3380 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3381 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3382 FILEDESC_SLOCK(fdp);
3384 /* root directory */
3385 if (fdp->fd_rdir != NULL) {
3387 data = fdp->fd_rdir;
3388 FILEDESC_SUNLOCK(fdp);
3389 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3390 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3391 FILEDESC_SLOCK(fdp);
3393 /* jail directory */
3394 if (fdp->fd_jdir != NULL) {
3396 data = fdp->fd_jdir;
3397 FILEDESC_SUNLOCK(fdp);
3398 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3399 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3400 FILEDESC_SLOCK(fdp);
3402 for (i = 0; i < fdp->fd_nfiles; i++) {
3403 if ((fp = fdp->fd_ofiles[i]) == NULL)
3411 * When reporting a capability, most fields will be from the
3412 * underlying object, but do mark as a capability and export
3413 * the capability rights mask.
3415 if (fp->f_type == DTYPE_CAPABILITY) {
3417 fd_cap_rights = cap_rights(fp);
3418 (void)cap_funwrap(fp, 0, &fp);
3420 #else /* !CAPABILITIES */
3421 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3422 ("sysctl_kern_proc_filedesc: saw capability"));
3424 switch (fp->f_type) {
3426 type = KF_TYPE_VNODE;
3432 type = KF_TYPE_SOCKET;
3437 type = KF_TYPE_PIPE;
3442 type = KF_TYPE_FIFO;
3448 type = KF_TYPE_KQUEUE;
3452 type = KF_TYPE_CRYPTO;
3456 type = KF_TYPE_MQUEUE;
3474 case DTYPE_PROCDESC:
3475 type = KF_TYPE_PROCDESC;
3481 type = KF_TYPE_UNKNOWN;
3484 refcnt = fp->f_count;
3485 fflags = fp->f_flag;
3486 offset = foffset_get(fp);
3489 * Create sysctl entry.
3490 * It is OK to drop the filedesc lock here as we will
3491 * re-validate and re-evaluate its properties when
3492 * the loop continues.
3494 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3495 FILEDESC_SUNLOCK(fdp);
3496 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3497 offset, fd_is_cap, fd_cap_rights, kif, sb, &remainder);
3498 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3499 FILEDESC_SLOCK(fdp);
3503 FILEDESC_SUNLOCK(fdp);
3511 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3514 * Get per-process file descriptors for use by procstat(1), et al.
3517 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3522 int error, error2, *name;
3526 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3527 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3532 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3533 error = kern_proc_filedesc_out(p, &sb, maxlen);
3534 error2 = sbuf_finish(&sb);
3536 return (error != 0 ? error : error2);
3540 vntype_to_kinfo(int vtype)
3545 } vtypes_table[] = {
3546 { VBAD, KF_VTYPE_VBAD },
3547 { VBLK, KF_VTYPE_VBLK },
3548 { VCHR, KF_VTYPE_VCHR },
3549 { VDIR, KF_VTYPE_VDIR },
3550 { VFIFO, KF_VTYPE_VFIFO },
3551 { VLNK, KF_VTYPE_VLNK },
3552 { VNON, KF_VTYPE_VNON },
3553 { VREG, KF_VTYPE_VREG },
3554 { VSOCK, KF_VTYPE_VSOCK }
3556 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3560 * Perform vtype translation.
3562 for (i = 0; i < NVTYPES; i++)
3563 if (vtypes_table[i].vtype == vtype)
3566 return (vtypes_table[i].kf_vtype);
3568 return (KF_VTYPE_UNKNOWN);
3572 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3575 char *fullpath, *freepath;
3576 int error, vfslocked;
3580 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3583 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3585 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3587 if (freepath != NULL)
3588 free(freepath, M_TEMP);
3591 * Retrieve vnode attributes.
3593 va.va_fsid = VNOVAL;
3595 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3596 vn_lock(vp, LK_SHARED | LK_RETRY);
3597 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3599 VFS_UNLOCK_GIANT(vfslocked);
3602 if (va.va_fsid != VNOVAL)
3603 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3605 kif->kf_un.kf_file.kf_file_fsid =
3606 vp->v_mount->mnt_stat.f_fsid.val[0];
3607 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3608 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3609 kif->kf_un.kf_file.kf_file_size = va.va_size;
3610 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3615 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3617 struct sockaddr *sa;
3618 struct inpcb *inpcb;
3619 struct unpcb *unpcb;
3624 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3625 kif->kf_sock_type = so->so_type;
3626 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3627 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3628 switch(kif->kf_sock_domain) {
3631 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3632 if (so->so_pcb != NULL) {
3633 inpcb = (struct inpcb *)(so->so_pcb);
3634 kif->kf_un.kf_sock.kf_sock_inpcb =
3635 (uintptr_t)inpcb->inp_ppcb;
3640 if (so->so_pcb != NULL) {
3641 unpcb = (struct unpcb *)(so->so_pcb);
3642 if (unpcb->unp_conn) {
3643 kif->kf_un.kf_sock.kf_sock_unpconn =
3644 (uintptr_t)unpcb->unp_conn;
3645 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3646 so->so_rcv.sb_state;
3647 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3648 so->so_snd.sb_state;
3653 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3654 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3655 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3658 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3659 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3660 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3663 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3664 sizeof(kif->kf_path));
3669 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3674 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3675 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3680 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3685 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3686 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3687 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3692 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3697 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3702 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3708 if (fp->f_data == NULL)
3710 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3712 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3713 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3714 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3718 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3719 sysctl_kern_proc_filedesc, "Process filedesc entries");
3723 * For the purposes of debugging, generate a human-readable string for the
3727 file_type_to_name(short type)
3757 * For the purposes of debugging, identify a process (if any, perhaps one of
3758 * many) that references the passed file in its file descriptor array. Return
3761 static struct proc *
3762 file_to_first_proc(struct file *fp)
3764 struct filedesc *fdp;
3768 FOREACH_PROC_IN_SYSTEM(p) {
3769 if (p->p_state == PRS_NEW)
3774 for (n = 0; n < fdp->fd_nfiles; n++) {
3775 if (fp == fdp->fd_ofiles[n])
3783 db_print_file(struct file *fp, int header)
3788 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3789 "File", "Type", "Data", "Flag", "GCFl", "Count",
3790 "MCount", "Vnode", "FPID", "FCmd");
3791 p = file_to_first_proc(fp);
3792 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3793 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3794 0, fp->f_count, 0, fp->f_vnode,
3795 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3798 DB_SHOW_COMMAND(file, db_show_file)
3803 db_printf("usage: show file <addr>\n");
3806 fp = (struct file *)addr;
3807 db_print_file(fp, 1);
3810 DB_SHOW_COMMAND(files, db_show_files)
3812 struct filedesc *fdp;
3819 FOREACH_PROC_IN_SYSTEM(p) {
3820 if (p->p_state == PRS_NEW)
3822 if ((fdp = p->p_fd) == NULL)
3824 for (n = 0; n < fdp->fd_nfiles; ++n) {
3825 if ((fp = fdp->fd_ofiles[n]) == NULL)
3827 db_print_file(fp, header);
3834 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3835 &maxfilesperproc, 0, "Maximum files allowed open per process");
3837 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3838 &maxfiles, 0, "Maximum number of files");
3840 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3841 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3845 filelistinit(void *dummy)
3848 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3849 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3850 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3851 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3853 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3855 /*-------------------------------------------------------------------*/
3858 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3859 int flags, struct thread *td)
3866 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3874 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3882 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3890 badfo_kqfilter(struct file *fp, struct knote *kn)
3897 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3905 badfo_close(struct file *fp, struct thread *td)
3912 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3920 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3927 struct fileops badfileops = {
3928 .fo_read = badfo_readwrite,
3929 .fo_write = badfo_readwrite,
3930 .fo_truncate = badfo_truncate,
3931 .fo_ioctl = badfo_ioctl,
3932 .fo_poll = badfo_poll,
3933 .fo_kqfilter = badfo_kqfilter,
3934 .fo_stat = badfo_stat,
3935 .fo_close = badfo_close,
3936 .fo_chmod = badfo_chmod,
3937 .fo_chown = badfo_chown,
3941 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3949 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3956 /*-------------------------------------------------------------------*/
3959 * File Descriptor pseudo-device driver (/dev/fd/).
3961 * Opening minor device N dup()s the file (if any) connected to file
3962 * descriptor N belonging to the calling process. Note that this driver
3963 * consists of only the ``open()'' routine, because all subsequent
3964 * references to this file will be direct to the other driver.
3966 * XXX: we could give this one a cloning event handler if necessary.
3971 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3975 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3976 * the file descriptor being sought for duplication. The error
3977 * return ensures that the vnode for this device will be released
3978 * by vn_open. Open will detect this special error and take the
3979 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3980 * will simply report the error.
3982 td->td_dupfd = dev2unit(dev);
3986 static struct cdevsw fildesc_cdevsw = {
3987 .d_version = D_VERSION,
3993 fildesc_drvinit(void *unused)
3997 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3998 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3999 make_dev_alias(dev, "stdin");
4000 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4001 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4002 make_dev_alias(dev, "stdout");
4003 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4004 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4005 make_dev_alias(dev, "stderr");
4008 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);