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>
74 #include <sys/signalvar.h>
75 #include <sys/socketvar.h>
78 #include <sys/syscallsubr.h>
79 #include <sys/sysctl.h>
80 #include <sys/sysproto.h>
82 #include <sys/unistd.h>
84 #include <sys/unpcb.h>
86 #include <sys/vnode.h>
88 #include <sys/ktrace.h>
93 #include <netinet/in.h>
94 #include <netinet/in_pcb.h>
96 #include <security/audit/audit.h>
103 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
104 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
105 "file desc to leader structures");
106 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
108 MALLOC_DECLARE(M_FADVISE);
110 static uma_zone_t file_zone;
113 /* Flags for do_dup() */
114 #define DUP_FIXED 0x1 /* Force fixed allocation */
115 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
116 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
118 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
119 struct thread *td, int holdleaders);
120 static int do_dup(struct thread *td, int flags, int old, int new,
122 static int fd_first_free(struct filedesc *fdp, int low, int size);
123 static int fd_last_used(struct filedesc *fdp, int size);
124 static void fdgrowtable(struct filedesc *fdp, int nfd);
125 static void fdunused(struct filedesc *fdp, int fd);
126 static void fdused(struct filedesc *fdp, int fd);
127 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
128 static int fill_procdesc_info(struct procdesc *pdp,
129 struct kinfo_file *kif);
130 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
131 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
132 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
133 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
138 * - An array of open file descriptors (fd_ofiles)
139 * - An array of file flags (fd_ofileflags)
140 * - A bitmap recording which descriptors are in use (fd_map)
142 * A process starts out with NDFILE descriptors. The value of NDFILE has
143 * been selected based the historical limit of 20 open files, and an
144 * assumption that the majority of processes, especially short-lived
145 * processes like shells, will never need more.
147 * If this initial allocation is exhausted, a larger descriptor table and
148 * map are allocated dynamically, and the pointers in the process's struct
149 * filedesc are updated to point to those. This is repeated every time
150 * the process runs out of file descriptors (provided it hasn't hit its
153 * Since threads may hold references to individual descriptor table
154 * entries, the tables are never freed. Instead, they are placed on a
155 * linked list and freed only when the struct filedesc is released.
158 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
159 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
160 #define NDSLOT(x) ((x) / NDENTRIES)
161 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
162 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
165 * SLIST entry used to keep track of ofiles which must be reclaimed when
169 struct file **ft_table;
170 SLIST_ENTRY(freetable) ft_next;
174 * Initial allocation: a filedesc structure + the head of SLIST used to
175 * keep track of old ofiles + enough space for NDFILE descriptors.
178 struct filedesc fd_fd;
179 SLIST_HEAD(, freetable) fd_free;
180 struct file *fd_dfiles[NDFILE];
181 char fd_dfileflags[NDFILE];
182 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
186 * Descriptor management.
188 volatile int openfiles; /* actual number of open files */
189 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
190 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
192 /* A mutex to protect the association between a proc and filedesc. */
193 static struct mtx fdesc_mtx;
196 * If low >= size, just return low. Otherwise find the first zero bit in the
197 * given bitmap, starting at low and not exceeding size - 1. Return size if
201 fd_first_free(struct filedesc *fdp, int low, int size)
203 NDSLOTTYPE *map = fdp->fd_map;
211 if (low % NDENTRIES) {
212 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
213 if ((mask &= ~map[off]) != 0UL)
214 return (off * NDENTRIES + ffsl(mask) - 1);
217 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
218 if (map[off] != ~0UL)
219 return (off * NDENTRIES + ffsl(~map[off]) - 1);
224 * Find the highest non-zero bit in the given bitmap, starting at 0 and
225 * not exceeding size - 1. Return -1 if not found.
228 fd_last_used(struct filedesc *fdp, int size)
230 NDSLOTTYPE *map = fdp->fd_map;
235 if (size % NDENTRIES) {
236 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
237 if ((mask &= map[off]) != 0)
238 return (off * NDENTRIES + flsl(mask) - 1);
241 for (minoff = NDSLOT(0); off >= minoff; --off)
243 return (off * NDENTRIES + flsl(map[off]) - 1);
248 fdisused(struct filedesc *fdp, int fd)
251 FILEDESC_LOCK_ASSERT(fdp);
253 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
254 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
256 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
260 * Mark a file descriptor as used.
263 fdused(struct filedesc *fdp, int fd)
266 FILEDESC_XLOCK_ASSERT(fdp);
268 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
270 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
271 if (fd > fdp->fd_lastfile)
272 fdp->fd_lastfile = fd;
273 if (fd == fdp->fd_freefile)
274 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
278 * Mark a file descriptor as unused.
281 fdunused(struct filedesc *fdp, int fd)
284 FILEDESC_XLOCK_ASSERT(fdp);
286 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
287 KASSERT(fdp->fd_ofiles[fd] == NULL, ("fd=%d is still in use", fd));
289 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
290 if (fd < fdp->fd_freefile)
291 fdp->fd_freefile = fd;
292 if (fd == fdp->fd_lastfile)
293 fdp->fd_lastfile = fd_last_used(fdp, fd);
297 * System calls on descriptors.
299 #ifndef _SYS_SYSPROTO_H_
300 struct getdtablesize_args {
306 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
308 struct proc *p = td->td_proc;
313 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
314 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
316 if (lim < td->td_retval[0])
317 td->td_retval[0] = lim;
322 * Duplicate a file descriptor to a particular value.
324 * Note: keep in mind that a potential race condition exists when closing
325 * descriptors from a shared descriptor table (via rfork).
327 #ifndef _SYS_SYSPROTO_H_
335 sys_dup2(struct thread *td, struct dup2_args *uap)
338 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
343 * Duplicate a file descriptor.
345 #ifndef _SYS_SYSPROTO_H_
352 sys_dup(struct thread *td, struct dup_args *uap)
355 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
359 * The file control system call.
361 #ifndef _SYS_SYSPROTO_H_
370 sys_fcntl(struct thread *td, struct fcntl_args *uap)
385 * Convert old flock structure to new.
387 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
388 fl.l_start = ofl.l_start;
389 fl.l_len = ofl.l_len;
390 fl.l_pid = ofl.l_pid;
391 fl.l_type = ofl.l_type;
392 fl.l_whence = ofl.l_whence;
412 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
421 error = kern_fcntl(td, uap->fd, cmd, arg);
424 if (uap->cmd == F_OGETLK) {
425 ofl.l_start = fl.l_start;
426 ofl.l_len = fl.l_len;
427 ofl.l_pid = fl.l_pid;
428 ofl.l_type = fl.l_type;
429 ofl.l_whence = fl.l_whence;
430 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
431 } else if (uap->cmd == F_GETLK) {
432 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
438 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
441 FILEDESC_LOCK_ASSERT(fdp);
443 *fpp = fget_locked(fdp, fd);
448 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
449 int err = cap_funwrap(*fpp, rights, fpp);
455 #endif /* CAPABILITIES */
460 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
462 struct filedesc *fdp;
481 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
484 case F_DUPFD_CLOEXEC:
486 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
492 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
495 case F_DUP2FD_CLOEXEC:
497 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
503 if ((fp = fget_locked(fdp, fd)) == NULL) {
504 FILEDESC_SUNLOCK(fdp);
508 pop = &fdp->fd_ofileflags[fd];
509 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
510 FILEDESC_SUNLOCK(fdp);
515 if ((fp = fget_locked(fdp, fd)) == NULL) {
516 FILEDESC_XUNLOCK(fdp);
520 pop = &fdp->fd_ofileflags[fd];
521 *pop = (*pop &~ UF_EXCLOSE) |
522 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
523 FILEDESC_XUNLOCK(fdp);
528 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
530 FILEDESC_SUNLOCK(fdp);
533 td->td_retval[0] = OFLAGS(fp->f_flag);
534 FILEDESC_SUNLOCK(fdp);
539 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
541 FILEDESC_SUNLOCK(fdp);
545 FILEDESC_SUNLOCK(fdp);
547 tmp = flg = fp->f_flag;
549 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
550 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
551 tmp = fp->f_flag & FNONBLOCK;
552 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
557 tmp = fp->f_flag & FASYNC;
558 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
563 atomic_clear_int(&fp->f_flag, FNONBLOCK);
565 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
571 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
573 FILEDESC_SUNLOCK(fdp);
577 FILEDESC_SUNLOCK(fdp);
578 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
580 td->td_retval[0] = tmp;
586 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
588 FILEDESC_SUNLOCK(fdp);
592 FILEDESC_SUNLOCK(fdp);
594 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
599 error = priv_check(td, PRIV_NFS_LOCKD);
607 /* FALLTHROUGH F_SETLK */
612 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
614 FILEDESC_SUNLOCK(fdp);
617 if (fp->f_type != DTYPE_VNODE) {
618 FILEDESC_SUNLOCK(fdp);
622 flp = (struct flock *)arg;
623 if (flp->l_whence == SEEK_CUR) {
624 foffset = foffset_get(fp);
627 foffset > OFF_MAX - flp->l_start)) {
628 FILEDESC_SUNLOCK(fdp);
632 flp->l_start += foffset;
636 * VOP_ADVLOCK() may block.
639 FILEDESC_SUNLOCK(fdp);
641 switch (flp->l_type) {
643 if ((fp->f_flag & FREAD) == 0) {
647 PROC_LOCK(p->p_leader);
648 p->p_leader->p_flag |= P_ADVLOCK;
649 PROC_UNLOCK(p->p_leader);
650 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
654 if ((fp->f_flag & FWRITE) == 0) {
658 PROC_LOCK(p->p_leader);
659 p->p_leader->p_flag |= P_ADVLOCK;
660 PROC_UNLOCK(p->p_leader);
661 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
665 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
670 * Temporary api for testing remote lock
673 if (flg != F_REMOTE) {
677 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
678 F_UNLCKSYS, flp, flg);
684 if (error != 0 || flp->l_type == F_UNLCK ||
685 flp->l_type == F_UNLCKSYS) {
691 * Check for a race with close.
693 * The vnode is now advisory locked (or unlocked, but this case
694 * is not really important) as the caller requested.
695 * We had to drop the filedesc lock, so we need to recheck if
696 * the descriptor is still valid, because if it was closed
697 * in the meantime we need to remove advisory lock from the
698 * vnode - close on any descriptor leading to an advisory
699 * locked vnode, removes that lock.
700 * We will return 0 on purpose in that case, as the result of
701 * successful advisory lock might have been externally visible
702 * already. This is fine - effectively we pretend to the caller
703 * that the closing thread was a bit slower and that the
704 * advisory lock succeeded before the close.
707 if (fget_locked(fdp, fd) != fp) {
708 FILEDESC_SUNLOCK(fdp);
709 flp->l_whence = SEEK_SET;
712 flp->l_type = F_UNLCK;
713 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
714 F_UNLCK, flp, F_POSIX);
716 FILEDESC_SUNLOCK(fdp);
722 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
724 FILEDESC_SUNLOCK(fdp);
727 if (fp->f_type != DTYPE_VNODE) {
728 FILEDESC_SUNLOCK(fdp);
732 flp = (struct flock *)arg;
733 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
734 flp->l_type != F_UNLCK) {
735 FILEDESC_SUNLOCK(fdp);
739 if (flp->l_whence == SEEK_CUR) {
740 foffset = foffset_get(fp);
741 if ((flp->l_start > 0 &&
742 foffset > OFF_MAX - flp->l_start) ||
744 foffset < OFF_MIN - flp->l_start)) {
745 FILEDESC_SUNLOCK(fdp);
749 flp->l_start += foffset;
752 * VOP_ADVLOCK() may block.
755 FILEDESC_SUNLOCK(fdp);
757 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
763 arg = arg ? 128 * 1024: 0;
767 if ((fp = fget_locked(fdp, fd)) == NULL) {
768 FILEDESC_SUNLOCK(fdp);
772 if (fp->f_type != DTYPE_VNODE) {
773 FILEDESC_SUNLOCK(fdp);
778 FILEDESC_SUNLOCK(fdp);
781 error = vn_lock(vp, LK_SHARED);
783 goto readahead_vnlock_fail;
784 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
786 fp->f_seqcount = (arg + bsize - 1) / bsize;
788 new = old = fp->f_flag;
790 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
791 readahead_vnlock_fail:;
794 new = old = fp->f_flag;
796 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
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;
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 (fget_locked(fdp, 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);
893 KASSERT(fp == fdp->fd_ofiles[old], ("old fd has been modified"));
894 KASSERT(old != new, ("new fd is same as old"));
896 delfp = fdp->fd_ofiles[new];
898 * Duplicate the source descriptor.
900 fdp->fd_ofiles[new] = fp;
901 if ((flags & DUP_CLOEXEC) != 0)
902 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
904 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
905 if (new > fdp->fd_lastfile)
906 fdp->fd_lastfile = new;
910 (void) closefp(fdp, new, delfp, td, 1);
911 /* closefp() drops the FILEDESC lock for us. */
913 FILEDESC_XUNLOCK(fdp);
920 * If sigio is on the list associated with a process or process group,
921 * disable signalling from the device, remove sigio from the list and
925 funsetown(struct sigio **sigiop)
935 *(sigio->sio_myref) = NULL;
936 if ((sigio)->sio_pgid < 0) {
937 struct pgrp *pg = (sigio)->sio_pgrp;
939 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
943 struct proc *p = (sigio)->sio_proc;
945 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
950 crfree(sigio->sio_ucred);
951 free(sigio, M_SIGIO);
955 * Free a list of sigio structures.
956 * We only need to lock the SIGIO_LOCK because we have made ourselves
957 * inaccessible to callers of fsetown and therefore do not need to lock
958 * the proc or pgrp struct for the list manipulation.
961 funsetownlst(struct sigiolst *sigiolst)
967 sigio = SLIST_FIRST(sigiolst);
974 * Every entry of the list should belong
975 * to a single proc or pgrp.
977 if (sigio->sio_pgid < 0) {
978 pg = sigio->sio_pgrp;
979 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
980 } else /* if (sigio->sio_pgid > 0) */ {
982 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
986 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
987 *(sigio->sio_myref) = NULL;
989 KASSERT(sigio->sio_pgid < 0,
990 ("Proc sigio in pgrp sigio list"));
991 KASSERT(sigio->sio_pgrp == pg,
992 ("Bogus pgrp in sigio list"));
994 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
997 } else /* if (p != NULL) */ {
998 KASSERT(sigio->sio_pgid > 0,
999 ("Pgrp sigio in proc sigio list"));
1000 KASSERT(sigio->sio_proc == p,
1001 ("Bogus proc in sigio list"));
1003 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1008 crfree(sigio->sio_ucred);
1009 free(sigio, M_SIGIO);
1016 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1018 * After permission checking, add a sigio structure to the sigio list for
1019 * the process or process group.
1022 fsetown(pid_t pgid, struct sigio **sigiop)
1026 struct sigio *sigio;
1036 /* Allocate and fill in the new sigio out of locks. */
1037 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1038 sigio->sio_pgid = pgid;
1039 sigio->sio_ucred = crhold(curthread->td_ucred);
1040 sigio->sio_myref = sigiop;
1042 sx_slock(&proctree_lock);
1051 * Policy - Don't allow a process to FSETOWN a process
1052 * in another session.
1054 * Remove this test to allow maximum flexibility or
1055 * restrict FSETOWN to the current process or process
1056 * group for maximum safety.
1059 if (proc->p_session != curthread->td_proc->p_session) {
1065 } else /* if (pgid < 0) */ {
1066 pgrp = pgfind(-pgid);
1074 * Policy - Don't allow a process to FSETOWN a process
1075 * in another session.
1077 * Remove this test to allow maximum flexibility or
1078 * restrict FSETOWN to the current process or process
1079 * group for maximum safety.
1081 if (pgrp->pg_session != curthread->td_proc->p_session) {
1092 * Since funsetownlst() is called without the proctree
1093 * locked, we need to check for P_WEXIT.
1094 * XXX: is ESRCH correct?
1096 if ((proc->p_flag & P_WEXIT) != 0) {
1101 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1102 sigio->sio_proc = proc;
1106 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1107 sigio->sio_pgrp = pgrp;
1110 sx_sunlock(&proctree_lock);
1117 sx_sunlock(&proctree_lock);
1118 crfree(sigio->sio_ucred);
1119 free(sigio, M_SIGIO);
1124 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1128 struct sigio **sigiop;
1133 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1139 * Function drops the filedesc lock on return.
1142 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1145 struct file *fp_object;
1148 FILEDESC_XLOCK_ASSERT(fdp);
1151 if (td->td_proc->p_fdtol != NULL) {
1153 * Ask fdfree() to sleep to ensure that all relevant
1154 * process leaders can be traversed in closef().
1156 fdp->fd_holdleaderscount++;
1163 * We now hold the fp reference that used to be owned by the
1164 * descriptor array. We have to unlock the FILEDESC *AFTER*
1165 * knote_fdclose to prevent a race of the fd getting opened, a knote
1166 * added, and deleteing a knote for the new fd.
1168 knote_fdclose(td, fd);
1171 * When we're closing an fd with a capability, we need to notify
1172 * mqueue if the underlying object is of type mqueue.
1174 (void)cap_funwrap(fp, 0, &fp_object);
1175 if (fp_object->f_type == DTYPE_MQUEUE)
1176 mq_fdclose(td, fd, fp_object);
1177 FILEDESC_XUNLOCK(fdp);
1179 error = closef(fp, td);
1181 FILEDESC_XLOCK(fdp);
1182 fdp->fd_holdleaderscount--;
1183 if (fdp->fd_holdleaderscount == 0 &&
1184 fdp->fd_holdleaderswakeup != 0) {
1185 fdp->fd_holdleaderswakeup = 0;
1186 wakeup(&fdp->fd_holdleaderscount);
1188 FILEDESC_XUNLOCK(fdp);
1194 * Close a file descriptor.
1196 #ifndef _SYS_SYSPROTO_H_
1205 struct close_args *uap;
1208 return (kern_close(td, uap->fd));
1216 struct filedesc *fdp;
1219 fdp = td->td_proc->p_fd;
1221 AUDIT_SYSCLOSE(td, fd);
1223 FILEDESC_XLOCK(fdp);
1224 if ((fp = fget_locked(fdp, fd)) == NULL) {
1225 FILEDESC_XUNLOCK(fdp);
1228 fdp->fd_ofiles[fd] = NULL;
1229 fdp->fd_ofileflags[fd] = 0;
1232 /* closefp() drops the FILEDESC lock for us. */
1233 return (closefp(fdp, fd, fp, td, 1));
1237 * Close open file descriptors.
1239 #ifndef _SYS_SYSPROTO_H_
1240 struct closefrom_args {
1246 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1248 struct filedesc *fdp;
1251 fdp = td->td_proc->p_fd;
1252 AUDIT_ARG_FD(uap->lowfd);
1255 * Treat negative starting file descriptor values identical to
1256 * closefrom(0) which closes all files.
1260 FILEDESC_SLOCK(fdp);
1261 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1262 if (fdp->fd_ofiles[fd] != NULL) {
1263 FILEDESC_SUNLOCK(fdp);
1264 (void)kern_close(td, fd);
1265 FILEDESC_SLOCK(fdp);
1268 FILEDESC_SUNLOCK(fdp);
1272 #if defined(COMPAT_43)
1274 * Return status information about a file descriptor.
1276 #ifndef _SYS_SYSPROTO_H_
1277 struct ofstat_args {
1284 ofstat(struct thread *td, struct ofstat_args *uap)
1290 error = kern_fstat(td, uap->fd, &ub);
1293 error = copyout(&oub, uap->sb, sizeof(oub));
1297 #endif /* COMPAT_43 */
1300 * Return status information about a file descriptor.
1302 #ifndef _SYS_SYSPROTO_H_
1310 sys_fstat(struct thread *td, struct fstat_args *uap)
1315 error = kern_fstat(td, uap->fd, &ub);
1317 error = copyout(&ub, uap->sb, sizeof(ub));
1322 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1329 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1332 AUDIT_ARG_FILE(td->td_proc, fp);
1334 error = fo_stat(fp, sbp, td->td_ucred, td);
1337 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1344 * Return status information about a file descriptor.
1346 #ifndef _SYS_SYSPROTO_H_
1347 struct nfstat_args {
1354 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1360 error = kern_fstat(td, uap->fd, &ub);
1362 cvtnstat(&ub, &nub);
1363 error = copyout(&nub, uap->sb, sizeof(nub));
1369 * Return pathconf information about a file descriptor.
1371 #ifndef _SYS_SYSPROTO_H_
1372 struct fpathconf_args {
1379 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1385 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1388 /* If asynchronous I/O is available, it works for all descriptors. */
1389 if (uap->name == _PC_ASYNC_IO) {
1390 td->td_retval[0] = async_io_version;
1395 vn_lock(vp, LK_SHARED | LK_RETRY);
1396 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1398 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1399 if (uap->name != _PC_PIPE_BUF) {
1402 td->td_retval[0] = PIPE_BUF;
1414 * Grow the file table to accomodate (at least) nfd descriptors.
1417 fdgrowtable(struct filedesc *fdp, int nfd)
1419 struct filedesc0 *fdp0;
1420 struct freetable *ft;
1421 struct file **ntable;
1422 struct file **otable;
1423 char *nfileflags, *ofileflags;
1424 int nnfiles, onfiles;
1425 NDSLOTTYPE *nmap, *omap;
1427 FILEDESC_XLOCK_ASSERT(fdp);
1429 KASSERT(fdp->fd_nfiles > 0,
1430 ("zero-length file table"));
1432 /* save old values */
1433 onfiles = fdp->fd_nfiles;
1434 otable = fdp->fd_ofiles;
1435 ofileflags = fdp->fd_ofileflags;
1438 /* compute the size of the new table */
1439 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1440 if (nnfiles <= onfiles)
1441 /* the table is already large enough */
1445 * Allocate a new table and map. We need enough space for a) the
1446 * file entries themselves, b) the file flags, and c) the struct
1447 * freetable we will use when we decommission the table and place
1448 * it on the freelist. We place the struct freetable in the
1449 * middle so we don't have to worry about padding.
1451 ntable = malloc(nnfiles * sizeof(*ntable) +
1452 sizeof(struct freetable) +
1453 nnfiles * sizeof(*nfileflags),
1454 M_FILEDESC, M_ZERO | M_WAITOK);
1455 nfileflags = (char *)&ntable[nnfiles] + sizeof(struct freetable);
1456 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1457 M_FILEDESC, M_ZERO | M_WAITOK);
1459 /* copy the old data over and point at the new tables */
1460 memcpy(ntable, otable, onfiles * sizeof(*otable));
1461 memcpy(nfileflags, ofileflags, onfiles * sizeof(*ofileflags));
1462 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1464 /* update the pointers and counters */
1465 fdp->fd_nfiles = nnfiles;
1466 fdp->fd_ofiles = ntable;
1467 fdp->fd_ofileflags = nfileflags;
1471 * Do not free the old file table, as some threads may still
1472 * reference entries within it. Instead, place it on a freelist
1473 * which will be processed when the struct filedesc is released.
1475 * Do, however, free the old map.
1477 * Note that if onfiles == NDFILE, we're dealing with the original
1478 * static allocation contained within (struct filedesc0 *)fdp,
1479 * which must not be freed.
1481 if (onfiles > NDFILE) {
1482 ft = (struct freetable *)&otable[onfiles];
1483 fdp0 = (struct filedesc0 *)fdp;
1484 ft->ft_table = otable;
1485 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1486 free(omap, M_FILEDESC);
1491 * Allocate a file descriptor for the process.
1494 fdalloc(struct thread *td, int minfd, int *result)
1496 struct proc *p = td->td_proc;
1497 struct filedesc *fdp = p->p_fd;
1498 int fd = -1, maxfd, allocfd;
1503 FILEDESC_XLOCK_ASSERT(fdp);
1505 if (fdp->fd_freefile > minfd)
1506 minfd = fdp->fd_freefile;
1509 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1513 * Search the bitmap for a free descriptor starting at minfd.
1514 * If none is found, grow the file table.
1516 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1519 if (fd >= fdp->fd_nfiles) {
1520 allocfd = min(fd * 2, maxfd);
1523 error = racct_set(p, RACCT_NOFILE, allocfd);
1529 * fd is already equal to first free descriptor >= minfd, so
1530 * we only need to grow the table and we are done.
1532 fdgrowtable(fdp, allocfd);
1536 * Perform some sanity checks, then mark the file descriptor as
1537 * used and return it to the caller.
1539 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1540 ("invalid descriptor %d", fd));
1541 KASSERT(!fdisused(fdp, fd),
1542 ("fd_first_free() returned non-free descriptor"));
1543 KASSERT(fdp->fd_ofiles[fd] == NULL, ("file descriptor isn't free"));
1544 KASSERT(fdp->fd_ofileflags[fd] == 0, ("file flags are set"));
1551 * Check to see whether n user file descriptors are available to the process
1555 fdavail(struct thread *td, int n)
1557 struct proc *p = td->td_proc;
1558 struct filedesc *fdp = td->td_proc->p_fd;
1561 FILEDESC_LOCK_ASSERT(fdp);
1564 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1565 * call racct_add() from there instead of dealing with containers
1569 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1571 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1573 last = min(fdp->fd_nfiles, lim);
1574 for (i = fdp->fd_freefile; i < last; i++) {
1575 if (fdp->fd_ofiles[i] == NULL && --n <= 0)
1582 * Create a new open file structure and allocate a file decriptor for the
1583 * process that refers to it. We add one reference to the file for the
1584 * descriptor table and one reference for resultfp. This is to prevent us
1585 * being preempted and the entry in the descriptor table closed after we
1586 * release the FILEDESC lock.
1589 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1594 error = falloc_noinstall(td, &fp);
1596 return (error); /* no reference held on error */
1598 error = finstall(td, fp, &fd, flags);
1600 fdrop(fp, td); /* one reference (fp only) */
1604 if (resultfp != NULL)
1605 *resultfp = fp; /* copy out result */
1607 fdrop(fp, td); /* release local reference */
1609 if (resultfd != NULL)
1616 * Create a new open file structure without allocating a file descriptor.
1619 falloc_noinstall(struct thread *td, struct file **resultfp)
1622 int maxuserfiles = maxfiles - (maxfiles / 20);
1623 static struct timeval lastfail;
1626 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1628 if ((openfiles >= maxuserfiles &&
1629 priv_check(td, PRIV_MAXFILES) != 0) ||
1630 openfiles >= maxfiles) {
1631 if (ppsratecheck(&lastfail, &curfail, 1)) {
1632 printf("kern.maxfiles limit exceeded by uid %i, "
1633 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1637 atomic_add_int(&openfiles, 1);
1638 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1639 refcount_init(&fp->f_count, 1);
1640 fp->f_cred = crhold(td->td_ucred);
1641 fp->f_ops = &badfileops;
1649 * Install a file in a file descriptor table.
1652 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1654 struct filedesc *fdp = td->td_proc->p_fd;
1657 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1658 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1660 FILEDESC_XLOCK(fdp);
1661 if ((error = fdalloc(td, 0, fd))) {
1662 FILEDESC_XUNLOCK(fdp);
1666 fdp->fd_ofiles[*fd] = fp;
1667 if ((flags & O_CLOEXEC) != 0)
1668 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1669 FILEDESC_XUNLOCK(fdp);
1674 * Build a new filedesc structure from another.
1675 * Copy the current, root, and jail root vnode references.
1678 fdinit(struct filedesc *fdp)
1680 struct filedesc0 *newfdp;
1682 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1683 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1685 FILEDESC_XLOCK(fdp);
1686 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1687 if (newfdp->fd_fd.fd_cdir)
1688 VREF(newfdp->fd_fd.fd_cdir);
1689 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1690 if (newfdp->fd_fd.fd_rdir)
1691 VREF(newfdp->fd_fd.fd_rdir);
1692 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1693 if (newfdp->fd_fd.fd_jdir)
1694 VREF(newfdp->fd_fd.fd_jdir);
1695 FILEDESC_XUNLOCK(fdp);
1698 /* Create the file descriptor table. */
1699 newfdp->fd_fd.fd_refcnt = 1;
1700 newfdp->fd_fd.fd_holdcnt = 1;
1701 newfdp->fd_fd.fd_cmask = CMASK;
1702 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1703 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1704 newfdp->fd_fd.fd_nfiles = NDFILE;
1705 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1706 newfdp->fd_fd.fd_lastfile = -1;
1707 return (&newfdp->fd_fd);
1710 static struct filedesc *
1711 fdhold(struct proc *p)
1713 struct filedesc *fdp;
1715 mtx_lock(&fdesc_mtx);
1719 mtx_unlock(&fdesc_mtx);
1724 fddrop(struct filedesc *fdp)
1726 struct filedesc0 *fdp0;
1727 struct freetable *ft;
1730 mtx_lock(&fdesc_mtx);
1731 i = --fdp->fd_holdcnt;
1732 mtx_unlock(&fdesc_mtx);
1736 FILEDESC_LOCK_DESTROY(fdp);
1737 fdp0 = (struct filedesc0 *)fdp;
1738 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1739 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1740 free(ft->ft_table, M_FILEDESC);
1742 free(fdp, M_FILEDESC);
1746 * Share a filedesc structure.
1749 fdshare(struct filedesc *fdp)
1752 FILEDESC_XLOCK(fdp);
1754 FILEDESC_XUNLOCK(fdp);
1759 * Unshare a filedesc structure, if necessary by making a copy
1762 fdunshare(struct proc *p, struct thread *td)
1765 FILEDESC_XLOCK(p->p_fd);
1766 if (p->p_fd->fd_refcnt > 1) {
1767 struct filedesc *tmp;
1769 FILEDESC_XUNLOCK(p->p_fd);
1770 tmp = fdcopy(p->p_fd);
1774 FILEDESC_XUNLOCK(p->p_fd);
1778 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1779 * this is to ease callers, not catch errors.
1782 fdcopy(struct filedesc *fdp)
1784 struct filedesc *newfdp;
1787 /* Certain daemons might not have file descriptors. */
1791 newfdp = fdinit(fdp);
1792 FILEDESC_SLOCK(fdp);
1793 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1794 FILEDESC_SUNLOCK(fdp);
1795 FILEDESC_XLOCK(newfdp);
1796 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1797 FILEDESC_XUNLOCK(newfdp);
1798 FILEDESC_SLOCK(fdp);
1800 /* copy all passable descriptors (i.e. not kqueue) */
1801 newfdp->fd_freefile = -1;
1802 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1803 if (fdisused(fdp, i) &&
1804 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1805 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1806 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1807 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1808 fhold(newfdp->fd_ofiles[i]);
1809 newfdp->fd_lastfile = i;
1811 if (newfdp->fd_freefile == -1)
1812 newfdp->fd_freefile = i;
1815 newfdp->fd_cmask = fdp->fd_cmask;
1816 FILEDESC_SUNLOCK(fdp);
1817 FILEDESC_XLOCK(newfdp);
1818 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1819 if (newfdp->fd_ofiles[i] != NULL)
1821 if (newfdp->fd_freefile == -1)
1822 newfdp->fd_freefile = i;
1823 FILEDESC_XUNLOCK(newfdp);
1828 * Release a filedesc structure.
1831 fdfree(struct thread *td)
1833 struct filedesc *fdp;
1835 struct filedesc_to_leader *fdtol;
1837 struct vnode *cdir, *jdir, *rdir, *vp;
1840 /* Certain daemons might not have file descriptors. */
1841 fdp = td->td_proc->p_fd;
1846 PROC_LOCK(td->td_proc);
1847 racct_set(td->td_proc, RACCT_NOFILE, 0);
1848 PROC_UNLOCK(td->td_proc);
1851 /* Check for special need to clear POSIX style locks */
1852 fdtol = td->td_proc->p_fdtol;
1853 if (fdtol != NULL) {
1854 FILEDESC_XLOCK(fdp);
1855 KASSERT(fdtol->fdl_refcount > 0,
1856 ("filedesc_to_refcount botch: fdl_refcount=%d",
1857 fdtol->fdl_refcount));
1858 if (fdtol->fdl_refcount == 1 &&
1859 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1860 for (i = 0; i <= fdp->fd_lastfile; i++) {
1861 fp = fdp->fd_ofiles[i];
1862 if (fp == NULL || fp->f_type != DTYPE_VNODE)
1865 FILEDESC_XUNLOCK(fdp);
1866 lf.l_whence = SEEK_SET;
1869 lf.l_type = F_UNLCK;
1871 (void) VOP_ADVLOCK(vp,
1872 (caddr_t)td->td_proc->p_leader, F_UNLCK,
1874 FILEDESC_XLOCK(fdp);
1879 if (fdtol->fdl_refcount == 1) {
1880 if (fdp->fd_holdleaderscount > 0 &&
1881 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1883 * close() or do_dup() has cleared a reference
1884 * in a shared file descriptor table.
1886 fdp->fd_holdleaderswakeup = 1;
1887 sx_sleep(&fdp->fd_holdleaderscount,
1888 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1891 if (fdtol->fdl_holdcount > 0) {
1893 * Ensure that fdtol->fdl_leader remains
1894 * valid in closef().
1896 fdtol->fdl_wakeup = 1;
1897 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1902 fdtol->fdl_refcount--;
1903 if (fdtol->fdl_refcount == 0 &&
1904 fdtol->fdl_holdcount == 0) {
1905 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1906 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1909 td->td_proc->p_fdtol = NULL;
1910 FILEDESC_XUNLOCK(fdp);
1912 free(fdtol, M_FILEDESC_TO_LEADER);
1914 FILEDESC_XLOCK(fdp);
1915 i = --fdp->fd_refcnt;
1916 FILEDESC_XUNLOCK(fdp);
1920 for (i = 0; i <= fdp->fd_lastfile; i++) {
1921 fp = fdp->fd_ofiles[i];
1923 FILEDESC_XLOCK(fdp);
1924 fdp->fd_ofiles[i] = NULL;
1925 FILEDESC_XUNLOCK(fdp);
1926 (void) closef(fp, td);
1929 FILEDESC_XLOCK(fdp);
1931 /* XXX This should happen earlier. */
1932 mtx_lock(&fdesc_mtx);
1933 td->td_proc->p_fd = NULL;
1934 mtx_unlock(&fdesc_mtx);
1936 if (fdp->fd_nfiles > NDFILE)
1937 free(fdp->fd_ofiles, M_FILEDESC);
1938 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1939 free(fdp->fd_map, M_FILEDESC);
1943 cdir = fdp->fd_cdir;
1944 fdp->fd_cdir = NULL;
1945 rdir = fdp->fd_rdir;
1946 fdp->fd_rdir = NULL;
1947 jdir = fdp->fd_jdir;
1948 fdp->fd_jdir = NULL;
1949 FILEDESC_XUNLOCK(fdp);
1962 * For setugid programs, we don't want to people to use that setugidness
1963 * to generate error messages which write to a file which otherwise would
1964 * otherwise be off-limits to the process. We check for filesystems where
1965 * the vnode can change out from under us after execve (like [lin]procfs).
1967 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1968 * sufficient. We also don't check for setugidness since we know we are.
1971 is_unsafe(struct file *fp)
1973 if (fp->f_type == DTYPE_VNODE) {
1974 struct vnode *vp = fp->f_vnode;
1976 if ((vp->v_vflag & VV_PROCDEP) != 0)
1983 * Make this setguid thing safe, if at all possible.
1986 setugidsafety(struct thread *td)
1988 struct filedesc *fdp;
1991 /* Certain daemons might not have file descriptors. */
1992 fdp = td->td_proc->p_fd;
1997 * Note: fdp->fd_ofiles may be reallocated out from under us while
1998 * we are blocked in a close. Be careful!
2000 FILEDESC_XLOCK(fdp);
2001 for (i = 0; i <= fdp->fd_lastfile; i++) {
2004 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2007 knote_fdclose(td, i);
2009 * NULL-out descriptor prior to close to avoid
2010 * a race while close blocks.
2012 fp = fdp->fd_ofiles[i];
2013 fdp->fd_ofiles[i] = NULL;
2014 fdp->fd_ofileflags[i] = 0;
2016 FILEDESC_XUNLOCK(fdp);
2017 (void) closef(fp, td);
2018 FILEDESC_XLOCK(fdp);
2021 FILEDESC_XUNLOCK(fdp);
2025 * If a specific file object occupies a specific file descriptor, close the
2026 * file descriptor entry and drop a reference on the file object. This is a
2027 * convenience function to handle a subsequent error in a function that calls
2028 * falloc() that handles the race that another thread might have closed the
2029 * file descriptor out from under the thread creating the file object.
2032 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2035 FILEDESC_XLOCK(fdp);
2036 if (fdp->fd_ofiles[idx] == fp) {
2037 fdp->fd_ofiles[idx] = NULL;
2039 FILEDESC_XUNLOCK(fdp);
2042 FILEDESC_XUNLOCK(fdp);
2046 * Close any files on exec?
2049 fdcloseexec(struct thread *td)
2051 struct filedesc *fdp;
2055 /* Certain daemons might not have file descriptors. */
2056 fdp = td->td_proc->p_fd;
2061 * We cannot cache fd_ofiles or fd_ofileflags since operations
2062 * may block and rip them out from under us.
2064 FILEDESC_XLOCK(fdp);
2065 for (i = 0; i <= fdp->fd_lastfile; i++) {
2066 fp = fdp->fd_ofiles[i];
2067 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2068 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2069 fdp->fd_ofiles[i] = NULL;
2070 fdp->fd_ofileflags[i] = 0;
2072 (void) closefp(fdp, i, fp, td, 0);
2073 /* closefp() drops the FILEDESC lock. */
2074 FILEDESC_XLOCK(fdp);
2077 FILEDESC_XUNLOCK(fdp);
2081 * It is unsafe for set[ug]id processes to be started with file
2082 * descriptors 0..2 closed, as these descriptors are given implicit
2083 * significance in the Standard C library. fdcheckstd() will create a
2084 * descriptor referencing /dev/null for each of stdin, stdout, and
2085 * stderr that is not already open.
2088 fdcheckstd(struct thread *td)
2090 struct filedesc *fdp;
2091 register_t retval, save;
2092 int i, error, devnull;
2094 fdp = td->td_proc->p_fd;
2097 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2100 for (i = 0; i < 3; i++) {
2101 if (fdp->fd_ofiles[i] != NULL)
2104 save = td->td_retval[0];
2105 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2107 devnull = td->td_retval[0];
2108 td->td_retval[0] = save;
2111 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2113 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2122 * Internal form of close. Decrement reference count on file structure.
2123 * Note: td may be NULL when closing a file that was being passed in a
2126 * XXXRW: Giant is not required for the caller, but often will be held; this
2127 * makes it moderately likely the Giant will be recursed in the VFS case.
2130 closef(struct file *fp, struct thread *td)
2134 struct filedesc_to_leader *fdtol;
2135 struct filedesc *fdp;
2136 struct file *fp_object;
2139 * POSIX record locking dictates that any close releases ALL
2140 * locks owned by this process. This is handled by setting
2141 * a flag in the unlock to free ONLY locks obeying POSIX
2142 * semantics, and not to free BSD-style file locks.
2143 * If the descriptor was in a message, POSIX-style locks
2144 * aren't passed with the descriptor, and the thread pointer
2145 * will be NULL. Callers should be careful only to pass a
2146 * NULL thread pointer when there really is no owning
2147 * context that might have locks, or the locks will be
2150 * If this is a capability, we do lock processing under the underlying
2151 * node, not the capability itself.
2153 (void)cap_funwrap(fp, 0, &fp_object);
2154 if (fp_object->f_type == DTYPE_VNODE && td != NULL) {
2155 vp = fp_object->f_vnode;
2156 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2157 lf.l_whence = SEEK_SET;
2160 lf.l_type = F_UNLCK;
2161 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2162 F_UNLCK, &lf, F_POSIX);
2164 fdtol = td->td_proc->p_fdtol;
2165 if (fdtol != NULL) {
2167 * Handle special case where file descriptor table is
2168 * shared between multiple process leaders.
2170 fdp = td->td_proc->p_fd;
2171 FILEDESC_XLOCK(fdp);
2172 for (fdtol = fdtol->fdl_next;
2173 fdtol != td->td_proc->p_fdtol;
2174 fdtol = fdtol->fdl_next) {
2175 if ((fdtol->fdl_leader->p_flag &
2178 fdtol->fdl_holdcount++;
2179 FILEDESC_XUNLOCK(fdp);
2180 lf.l_whence = SEEK_SET;
2183 lf.l_type = F_UNLCK;
2184 vp = fp_object->f_vnode;
2185 (void) VOP_ADVLOCK(vp,
2186 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2188 FILEDESC_XLOCK(fdp);
2189 fdtol->fdl_holdcount--;
2190 if (fdtol->fdl_holdcount == 0 &&
2191 fdtol->fdl_wakeup != 0) {
2192 fdtol->fdl_wakeup = 0;
2196 FILEDESC_XUNLOCK(fdp);
2199 return (fdrop(fp, td));
2203 * Initialize the file pointer with the specified properties.
2205 * The ops are set with release semantics to be certain that the flags, type,
2206 * and data are visible when ops is. This is to prevent ops methods from being
2207 * called with bad data.
2210 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2215 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2219 fget_unlocked(struct filedesc *fdp, int fd)
2224 if (fd < 0 || fd >= fdp->fd_nfiles)
2227 * Fetch the descriptor locklessly. We avoid fdrop() races by
2228 * never raising a refcount above 0. To accomplish this we have
2229 * to use a cmpset loop rather than an atomic_add. The descriptor
2230 * must be re-verified once we acquire a reference to be certain
2231 * that the identity is still correct and we did not lose a race
2232 * due to preemption.
2235 fp = fdp->fd_ofiles[fd];
2238 count = fp->f_count;
2242 * Use an acquire barrier to prevent caching of fd_ofiles
2243 * so it is refreshed for verification.
2245 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2247 if (fp == fdp->fd_ofiles[fd])
2249 fdrop(fp, curthread);
2256 * Extract the file pointer associated with the specified descriptor for the
2257 * current user process.
2259 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2262 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2263 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2264 * Otherwise, if the file is a capability, its rights will be checked against
2265 * the capability rights mask, and if successful, the object will be unwrapped.
2267 * If an error occured the non-zero error is returned and *fpp is set to
2268 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2269 * responsible for fdrop().
2271 #define FGET_GETCAP 0x00000001
2273 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2274 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2277 struct filedesc *fdp;
2280 struct file *fp_fromcap;
2285 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2287 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2289 if (fp->f_ops == &badfileops) {
2296 * If this is a capability, what rights does it have?
2298 if (haverightsp != NULL) {
2299 if (fp->f_type == DTYPE_CAPABILITY)
2300 *haverightsp = cap_rights(fp);
2302 *haverightsp = CAP_MASK_VALID;
2306 * If a capability has been requested, return the capability directly.
2307 * Otherwise, check capability rights, extract the underlying object,
2308 * and check its access flags.
2310 if (fget_flags & FGET_GETCAP) {
2311 if (fp->f_type != DTYPE_CAPABILITY) {
2316 if (maxprotp == NULL)
2317 error = cap_funwrap(fp, needrights, &fp_fromcap);
2319 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2327 * If we've unwrapped a file, drop the original capability
2328 * and hold the new descriptor. fp after this point refers to
2329 * the actual (unwrapped) object, not the capability.
2331 if (fp != fp_fromcap) {
2337 #else /* !CAPABILITIES */
2338 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2339 ("%s: saw capability", __func__));
2340 if (maxprotp != NULL)
2341 *maxprotp = VM_PROT_ALL;
2342 #endif /* CAPABILITIES */
2345 * FREAD and FWRITE failure return EBADF as per POSIX.
2351 if ((fp->f_flag & flags) == 0)
2355 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2356 ((fp->f_flag & FWRITE) != 0))
2362 KASSERT(0, ("wrong flags"));
2375 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2378 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2382 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2386 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2390 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2393 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2397 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2400 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2404 * Unlike the other fget() calls, which accept and check capability rights
2405 * but never return capabilities, fgetcap() returns the capability but doesn't
2406 * check capability rights.
2409 fgetcap(struct thread *td, int fd, struct file **fpp)
2412 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2417 * Like fget() but loads the underlying vnode, or returns an error if the
2418 * descriptor does not represent a vnode. Note that pipes use vnodes but
2419 * never have VM objects. The returned vnode will be vref()'d.
2421 * XXX: what about the unused flags ?
2424 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2425 cap_rights_t *haverightsp, struct vnode **vpp)
2431 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2434 if (fp->f_vnode == NULL) {
2446 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2449 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2453 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2456 return (_fgetvp(td, fd, 0, need, have, vpp));
2460 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2463 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2467 fgetvp_exec(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2470 return (_fgetvp(td, fd, FEXEC, rights, NULL, vpp));
2475 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2479 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2484 * Like fget() but loads the underlying socket, or returns an error if the
2485 * descriptor does not represent a socket.
2487 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2490 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2491 * on their file descriptor reference to prevent the socket from being free'd
2495 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2504 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2506 if (fp->f_type != DTYPE_SOCKET) {
2511 *fflagp = fp->f_flag;
2522 * Drop the reference count on the socket and XXX release the SX lock in the
2523 * future. The last reference closes the socket.
2525 * Note: fputsock() is deprecated, see comment for fgetsock().
2528 fputsock(struct socket *so)
2533 CURVNET_SET(so->so_vnet);
2539 * Handle the last reference to a file being closed.
2541 * No special capability handling here, as the capability's fo_close will run
2542 * instead of the object here, and perform any necessary drop on the object.
2545 _fdrop(struct file *fp, struct thread *td)
2550 if (fp->f_count != 0)
2551 panic("fdrop: count %d", fp->f_count);
2552 if (fp->f_ops != &badfileops)
2553 error = fo_close(fp, td);
2554 atomic_subtract_int(&openfiles, 1);
2556 free(fp->f_advice, M_FADVISE);
2557 uma_zfree(file_zone, fp);
2563 * Apply an advisory lock on a file descriptor.
2565 * Just attempt to get a record lock of the requested type on the entire file
2566 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2568 #ifndef _SYS_SYSPROTO_H_
2576 sys_flock(struct thread *td, struct flock_args *uap)
2583 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2585 if (fp->f_type != DTYPE_VNODE) {
2587 return (EOPNOTSUPP);
2591 lf.l_whence = SEEK_SET;
2594 if (uap->how & LOCK_UN) {
2595 lf.l_type = F_UNLCK;
2596 atomic_clear_int(&fp->f_flag, FHASLOCK);
2597 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2600 if (uap->how & LOCK_EX)
2601 lf.l_type = F_WRLCK;
2602 else if (uap->how & LOCK_SH)
2603 lf.l_type = F_RDLCK;
2608 atomic_set_int(&fp->f_flag, FHASLOCK);
2609 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2610 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2616 * Duplicate the specified descriptor to a free descriptor.
2619 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode, int openerror, int *indxp)
2624 KASSERT(openerror == ENODEV || openerror == ENXIO,
2625 ("unexpected error %d in %s", openerror, __func__));
2628 * If the to-be-dup'd fd number is greater than the allowed number
2629 * of file descriptors, or the fd to be dup'd has already been
2630 * closed, then reject.
2632 FILEDESC_XLOCK(fdp);
2633 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2634 FILEDESC_XUNLOCK(fdp);
2638 error = fdalloc(td, 0, &indx);
2640 FILEDESC_XUNLOCK(fdp);
2645 * There are two cases of interest here.
2647 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2649 * For ENXIO steal away the file structure from (dfd) and store it in
2650 * (indx). (dfd) is effectively closed by this operation.
2652 switch (openerror) {
2655 * Check that the mode the file is being opened for is a
2656 * subset of the mode of the existing descriptor.
2658 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2659 fdunused(fdp, indx);
2660 FILEDESC_XUNLOCK(fdp);
2663 fdp->fd_ofiles[indx] = fp;
2664 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2669 * Steal away the file pointer from dfd and stuff it into indx.
2671 fdp->fd_ofiles[indx] = fp;
2672 fdp->fd_ofiles[dfd] = NULL;
2673 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2674 fdp->fd_ofileflags[dfd] = 0;
2678 FILEDESC_XUNLOCK(fdp);
2684 * Scan all active processes and prisons to see if any of them have a current
2685 * or root directory of `olddp'. If so, replace them with the new mount point.
2688 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2690 struct filedesc *fdp;
2695 if (vrefcnt(olddp) == 1)
2698 sx_slock(&allproc_lock);
2699 FOREACH_PROC_IN_SYSTEM(p) {
2703 FILEDESC_XLOCK(fdp);
2704 if (fdp->fd_cdir == olddp) {
2706 fdp->fd_cdir = newdp;
2709 if (fdp->fd_rdir == olddp) {
2711 fdp->fd_rdir = newdp;
2714 if (fdp->fd_jdir == olddp) {
2716 fdp->fd_jdir = newdp;
2719 FILEDESC_XUNLOCK(fdp);
2722 sx_sunlock(&allproc_lock);
2723 if (rootvnode == olddp) {
2728 mtx_lock(&prison0.pr_mtx);
2729 if (prison0.pr_root == olddp) {
2731 prison0.pr_root = newdp;
2734 mtx_unlock(&prison0.pr_mtx);
2735 sx_slock(&allprison_lock);
2736 TAILQ_FOREACH(pr, &allprison, pr_list) {
2737 mtx_lock(&pr->pr_mtx);
2738 if (pr->pr_root == olddp) {
2740 pr->pr_root = newdp;
2743 mtx_unlock(&pr->pr_mtx);
2745 sx_sunlock(&allprison_lock);
2750 struct filedesc_to_leader *
2751 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2753 struct filedesc_to_leader *fdtol;
2755 fdtol = malloc(sizeof(struct filedesc_to_leader),
2756 M_FILEDESC_TO_LEADER,
2758 fdtol->fdl_refcount = 1;
2759 fdtol->fdl_holdcount = 0;
2760 fdtol->fdl_wakeup = 0;
2761 fdtol->fdl_leader = leader;
2763 FILEDESC_XLOCK(fdp);
2764 fdtol->fdl_next = old->fdl_next;
2765 fdtol->fdl_prev = old;
2766 old->fdl_next = fdtol;
2767 fdtol->fdl_next->fdl_prev = fdtol;
2768 FILEDESC_XUNLOCK(fdp);
2770 fdtol->fdl_next = fdtol;
2771 fdtol->fdl_prev = fdtol;
2777 * Get file structures globally.
2780 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2783 struct filedesc *fdp;
2788 error = sysctl_wire_old_buffer(req, 0);
2791 if (req->oldptr == NULL) {
2793 sx_slock(&allproc_lock);
2794 FOREACH_PROC_IN_SYSTEM(p) {
2795 if (p->p_state == PRS_NEW)
2800 /* overestimates sparse tables. */
2801 if (fdp->fd_lastfile > 0)
2802 n += fdp->fd_lastfile;
2805 sx_sunlock(&allproc_lock);
2806 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2809 bzero(&xf, sizeof(xf));
2810 xf.xf_size = sizeof(xf);
2811 sx_slock(&allproc_lock);
2812 FOREACH_PROC_IN_SYSTEM(p) {
2814 if (p->p_state == PRS_NEW) {
2818 if (p_cansee(req->td, p) != 0) {
2822 xf.xf_pid = p->p_pid;
2823 xf.xf_uid = p->p_ucred->cr_uid;
2828 FILEDESC_SLOCK(fdp);
2829 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2830 if ((fp = fdp->fd_ofiles[n]) == NULL)
2834 xf.xf_data = fp->f_data;
2835 xf.xf_vnode = fp->f_vnode;
2836 xf.xf_type = fp->f_type;
2837 xf.xf_count = fp->f_count;
2839 xf.xf_offset = foffset_get(fp);
2840 xf.xf_flag = fp->f_flag;
2841 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2845 FILEDESC_SUNLOCK(fdp);
2850 sx_sunlock(&allproc_lock);
2854 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2855 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2857 #ifdef KINFO_OFILE_SIZE
2858 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2861 #ifdef COMPAT_FREEBSD7
2863 export_vnode_for_osysctl(struct vnode *vp, int type,
2864 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2867 char *fullpath, *freepath;
2869 bzero(kif, sizeof(*kif));
2870 kif->kf_structsize = sizeof(*kif);
2874 kif->kf_type = KF_TYPE_VNODE;
2875 /* This function only handles directories. */
2876 if (vp->v_type != VDIR) {
2880 kif->kf_vnode_type = KF_VTYPE_VDIR;
2883 * This is not a true file descriptor, so we set a bogus refcount
2884 * and offset to indicate these fields should be ignored.
2886 kif->kf_ref_count = -1;
2887 kif->kf_offset = -1;
2891 FILEDESC_SUNLOCK(fdp);
2892 vn_fullpath(curthread, vp, &fullpath, &freepath);
2894 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2895 if (freepath != NULL)
2896 free(freepath, M_TEMP);
2897 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2898 FILEDESC_SLOCK(fdp);
2903 * Get per-process file descriptors for use by procstat(1), et al.
2906 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2908 char *fullpath, *freepath;
2909 struct kinfo_ofile *kif;
2910 struct filedesc *fdp;
2911 int error, i, *name;
2912 struct shmfd *shmfd;
2920 if ((p = pfind((pid_t)name[0])) == NULL)
2922 if ((error = p_candebug(curthread, p))) {
2930 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2931 FILEDESC_SLOCK(fdp);
2932 if (fdp->fd_cdir != NULL)
2933 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2935 if (fdp->fd_rdir != NULL)
2936 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2938 if (fdp->fd_jdir != NULL)
2939 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2941 for (i = 0; i < fdp->fd_nfiles; i++) {
2942 if ((fp = fdp->fd_ofiles[i]) == NULL)
2944 bzero(kif, sizeof(*kif));
2945 kif->kf_structsize = sizeof(*kif);
2954 * When reporting a capability, most fields will be from the
2955 * underlying object, but do mark as a capability. With
2956 * ofiledesc, we don't have a field to export the cap_rights_t,
2957 * but we do with the new filedesc.
2959 if (fp->f_type == DTYPE_CAPABILITY) {
2960 kif->kf_flags |= KF_FLAG_CAPABILITY;
2961 (void)cap_funwrap(fp, 0, &fp);
2964 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2965 ("sysctl_kern_proc_ofiledesc: saw capability"));
2967 switch (fp->f_type) {
2969 kif->kf_type = KF_TYPE_VNODE;
2974 kif->kf_type = KF_TYPE_SOCKET;
2979 kif->kf_type = KF_TYPE_PIPE;
2983 kif->kf_type = KF_TYPE_FIFO;
2988 kif->kf_type = KF_TYPE_KQUEUE;
2992 kif->kf_type = KF_TYPE_CRYPTO;
2996 kif->kf_type = KF_TYPE_MQUEUE;
3000 kif->kf_type = KF_TYPE_SHM;
3005 kif->kf_type = KF_TYPE_SEM;
3009 kif->kf_type = KF_TYPE_PTS;
3014 case DTYPE_PROCDESC:
3015 kif->kf_type = KF_TYPE_PROCDESC;
3020 kif->kf_type = KF_TYPE_UNKNOWN;
3023 kif->kf_ref_count = fp->f_count;
3024 if (fp->f_flag & FREAD)
3025 kif->kf_flags |= KF_FLAG_READ;
3026 if (fp->f_flag & FWRITE)
3027 kif->kf_flags |= KF_FLAG_WRITE;
3028 if (fp->f_flag & FAPPEND)
3029 kif->kf_flags |= KF_FLAG_APPEND;
3030 if (fp->f_flag & FASYNC)
3031 kif->kf_flags |= KF_FLAG_ASYNC;
3032 if (fp->f_flag & FFSYNC)
3033 kif->kf_flags |= KF_FLAG_FSYNC;
3034 if (fp->f_flag & FNONBLOCK)
3035 kif->kf_flags |= KF_FLAG_NONBLOCK;
3036 if (fp->f_flag & O_DIRECT)
3037 kif->kf_flags |= KF_FLAG_DIRECT;
3038 if (fp->f_flag & FHASLOCK)
3039 kif->kf_flags |= KF_FLAG_HASLOCK;
3040 kif->kf_offset = foffset_get(fp);
3043 switch (vp->v_type) {
3045 kif->kf_vnode_type = KF_VTYPE_VNON;
3048 kif->kf_vnode_type = KF_VTYPE_VREG;
3051 kif->kf_vnode_type = KF_VTYPE_VDIR;
3054 kif->kf_vnode_type = KF_VTYPE_VBLK;
3057 kif->kf_vnode_type = KF_VTYPE_VCHR;
3060 kif->kf_vnode_type = KF_VTYPE_VLNK;
3063 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3066 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3069 kif->kf_vnode_type = KF_VTYPE_VBAD;
3072 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3076 * It is OK to drop the filedesc lock here as we will
3077 * re-validate and re-evaluate its properties when
3078 * the loop continues.
3082 FILEDESC_SUNLOCK(fdp);
3083 vn_fullpath(curthread, vp, &fullpath, &freepath);
3085 strlcpy(kif->kf_path, fullpath,
3086 sizeof(kif->kf_path));
3087 if (freepath != NULL)
3088 free(freepath, M_TEMP);
3089 FILEDESC_SLOCK(fdp);
3092 struct sockaddr *sa;
3094 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3095 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3096 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3099 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3100 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3101 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3104 kif->kf_sock_domain =
3105 so->so_proto->pr_domain->dom_family;
3106 kif->kf_sock_type = so->so_type;
3107 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3110 strlcpy(kif->kf_path, tty_devname(tp),
3111 sizeof(kif->kf_path));
3114 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3115 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3119 FILEDESC_SUNLOCK(fdp);
3125 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3126 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3127 #endif /* COMPAT_FREEBSD7 */
3129 #ifdef KINFO_FILE_SIZE
3130 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3134 export_fd_for_sysctl(void *data, int type, int fd, int fflags, int refcnt,
3135 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3136 struct kinfo_file *kif, struct sysctl_req *req)
3141 } fflags_table[] = {
3142 { FAPPEND, KF_FLAG_APPEND },
3143 { FASYNC, KF_FLAG_ASYNC },
3144 { FFSYNC, KF_FLAG_FSYNC },
3145 { FHASLOCK, KF_FLAG_HASLOCK },
3146 { FNONBLOCK, KF_FLAG_NONBLOCK },
3147 { FREAD, KF_FLAG_READ },
3148 { FWRITE, KF_FLAG_WRITE },
3149 { O_CREAT, KF_FLAG_CREAT },
3150 { O_DIRECT, KF_FLAG_DIRECT },
3151 { O_EXCL, KF_FLAG_EXCL },
3152 { O_EXEC, KF_FLAG_EXEC },
3153 { O_EXLOCK, KF_FLAG_EXLOCK },
3154 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3155 { O_SHLOCK, KF_FLAG_SHLOCK },
3156 { O_TRUNC, KF_FLAG_TRUNC }
3158 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3163 bzero(kif, sizeof(*kif));
3167 vp = (struct vnode *)data;
3168 error = fill_vnode_info(vp, kif);
3171 case KF_TYPE_SOCKET:
3172 error = fill_socket_info((struct socket *)data, kif);
3175 error = fill_pipe_info((struct pipe *)data, kif);
3178 error = fill_pts_info((struct tty *)data, kif);
3180 case KF_TYPE_PROCDESC:
3181 error = fill_procdesc_info((struct procdesc *)data, kif);
3184 error = fill_shm_info((struct file *)data, kif);
3190 kif->kf_status |= KF_ATTR_VALID;
3193 * Translate file access flags.
3195 for (i = 0; i < NFFLAGS; i++)
3196 if (fflags & fflags_table[i].fflag)
3197 kif->kf_flags |= fflags_table[i].kf_fflag;
3199 kif->kf_flags |= KF_FLAG_CAPABILITY;
3201 kif->kf_cap_rights = fd_cap_rights;
3203 kif->kf_type = type;
3204 kif->kf_ref_count = refcnt;
3205 kif->kf_offset = offset;
3206 /* Pack record size down */
3207 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3208 strlen(kif->kf_path) + 1;
3209 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3210 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3215 * Get per-process file descriptors for use by procstat(1), et al.
3218 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3221 struct filedesc *fdp;
3222 struct kinfo_file *kif;
3224 struct vnode *cttyvp, *textvp, *tracevp;
3228 int error, i, *name;
3229 int fd_is_cap, type, refcnt, fflags;
3230 cap_rights_t fd_cap_rights;
3233 if ((p = pfind((pid_t)name[0])) == NULL)
3235 if ((error = p_candebug(curthread, p))) {
3240 tracevp = p->p_tracevp;
3241 if (tracevp != NULL)
3244 textvp = p->p_textvp;
3247 /* Controlling tty. */
3249 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3250 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3256 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3257 if (tracevp != NULL)
3258 export_fd_for_sysctl(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3259 FREAD | FWRITE, -1, -1, 0, 0, kif, req);
3261 export_fd_for_sysctl(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3262 FREAD, -1, -1, 0, 0, kif, req);
3264 export_fd_for_sysctl(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3265 FREAD | FWRITE, -1, -1, 0, 0, kif, req);
3268 FILEDESC_SLOCK(fdp);
3269 /* working directory */
3270 if (fdp->fd_cdir != NULL) {
3272 data = fdp->fd_cdir;
3273 FILEDESC_SUNLOCK(fdp);
3274 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3275 FREAD, -1, -1, 0, 0, kif, req);
3276 FILEDESC_SLOCK(fdp);
3278 /* root directory */
3279 if (fdp->fd_rdir != NULL) {
3281 data = fdp->fd_rdir;
3282 FILEDESC_SUNLOCK(fdp);
3283 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3284 FREAD, -1, -1, 0, 0, kif, req);
3285 FILEDESC_SLOCK(fdp);
3287 /* jail directory */
3288 if (fdp->fd_jdir != NULL) {
3290 data = fdp->fd_jdir;
3291 FILEDESC_SUNLOCK(fdp);
3292 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3293 FREAD, -1, -1, 0, 0, kif, req);
3294 FILEDESC_SLOCK(fdp);
3296 for (i = 0; i < fdp->fd_nfiles; i++) {
3297 if ((fp = fdp->fd_ofiles[i]) == NULL)
3305 * When reporting a capability, most fields will be from the
3306 * underlying object, but do mark as a capability and export
3307 * the capability rights mask.
3309 if (fp->f_type == DTYPE_CAPABILITY) {
3311 fd_cap_rights = cap_rights(fp);
3312 (void)cap_funwrap(fp, 0, &fp);
3314 #else /* !CAPABILITIES */
3315 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3316 ("sysctl_kern_proc_filedesc: saw capability"));
3318 switch (fp->f_type) {
3320 type = KF_TYPE_VNODE;
3326 type = KF_TYPE_SOCKET;
3331 type = KF_TYPE_PIPE;
3336 type = KF_TYPE_FIFO;
3342 type = KF_TYPE_KQUEUE;
3346 type = KF_TYPE_CRYPTO;
3350 type = KF_TYPE_MQUEUE;
3368 case DTYPE_PROCDESC:
3369 type = KF_TYPE_PROCDESC;
3375 type = KF_TYPE_UNKNOWN;
3378 refcnt = fp->f_count;
3379 fflags = fp->f_flag;
3380 offset = foffset_get(fp);
3383 * Create sysctl entry.
3384 * It is OK to drop the filedesc lock here as we will
3385 * re-validate and re-evaluate its properties when
3386 * the loop continues.
3388 oldidx = req->oldidx;
3389 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3390 FILEDESC_SUNLOCK(fdp);
3391 error = export_fd_for_sysctl(data, type, i, fflags, refcnt,
3392 offset, fd_is_cap, fd_cap_rights, kif, req);
3393 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3394 FILEDESC_SLOCK(fdp);
3396 if (error == ENOMEM) {
3398 * The hack to keep the ABI of sysctl
3399 * kern.proc.filedesc intact, but not
3400 * to account a partially copied
3401 * kinfo_file into the oldidx.
3403 req->oldidx = oldidx;
3409 FILEDESC_SUNLOCK(fdp);
3418 vntype_to_kinfo(int vtype)
3423 } vtypes_table[] = {
3424 { VBAD, KF_VTYPE_VBAD },
3425 { VBLK, KF_VTYPE_VBLK },
3426 { VCHR, KF_VTYPE_VCHR },
3427 { VDIR, KF_VTYPE_VDIR },
3428 { VFIFO, KF_VTYPE_VFIFO },
3429 { VLNK, KF_VTYPE_VLNK },
3430 { VNON, KF_VTYPE_VNON },
3431 { VREG, KF_VTYPE_VREG },
3432 { VSOCK, KF_VTYPE_VSOCK }
3434 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3438 * Perform vtype translation.
3440 for (i = 0; i < NVTYPES; i++)
3441 if (vtypes_table[i].vtype == vtype)
3444 return (vtypes_table[i].kf_vtype);
3446 return (KF_VTYPE_UNKNOWN);
3450 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3453 char *fullpath, *freepath;
3458 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3461 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3463 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3465 if (freepath != NULL)
3466 free(freepath, M_TEMP);
3469 * Retrieve vnode attributes.
3471 va.va_fsid = VNOVAL;
3473 vn_lock(vp, LK_SHARED | LK_RETRY);
3474 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3478 if (va.va_fsid != VNOVAL)
3479 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3481 kif->kf_un.kf_file.kf_file_fsid =
3482 vp->v_mount->mnt_stat.f_fsid.val[0];
3483 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3484 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3485 kif->kf_un.kf_file.kf_file_size = va.va_size;
3486 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3491 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3493 struct sockaddr *sa;
3494 struct inpcb *inpcb;
3495 struct unpcb *unpcb;
3500 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3501 kif->kf_sock_type = so->so_type;
3502 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3503 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3504 switch(kif->kf_sock_domain) {
3507 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3508 if (so->so_pcb != NULL) {
3509 inpcb = (struct inpcb *)(so->so_pcb);
3510 kif->kf_un.kf_sock.kf_sock_inpcb =
3511 (uintptr_t)inpcb->inp_ppcb;
3516 if (so->so_pcb != NULL) {
3517 unpcb = (struct unpcb *)(so->so_pcb);
3518 if (unpcb->unp_conn) {
3519 kif->kf_un.kf_sock.kf_sock_unpconn =
3520 (uintptr_t)unpcb->unp_conn;
3521 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3522 so->so_rcv.sb_state;
3523 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3524 so->so_snd.sb_state;
3529 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3530 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3531 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3534 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3535 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3536 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3539 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3540 sizeof(kif->kf_path));
3545 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3550 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3551 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3556 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3561 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3562 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3563 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3568 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3573 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3578 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3584 if (fp->f_data == NULL)
3586 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3588 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3589 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3590 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3594 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3595 sysctl_kern_proc_filedesc, "Process filedesc entries");
3599 * For the purposes of debugging, generate a human-readable string for the
3603 file_type_to_name(short type)
3633 * For the purposes of debugging, identify a process (if any, perhaps one of
3634 * many) that references the passed file in its file descriptor array. Return
3637 static struct proc *
3638 file_to_first_proc(struct file *fp)
3640 struct filedesc *fdp;
3644 FOREACH_PROC_IN_SYSTEM(p) {
3645 if (p->p_state == PRS_NEW)
3650 for (n = 0; n < fdp->fd_nfiles; n++) {
3651 if (fp == fdp->fd_ofiles[n])
3659 db_print_file(struct file *fp, int header)
3664 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3665 "File", "Type", "Data", "Flag", "GCFl", "Count",
3666 "MCount", "Vnode", "FPID", "FCmd");
3667 p = file_to_first_proc(fp);
3668 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3669 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3670 0, fp->f_count, 0, fp->f_vnode,
3671 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3674 DB_SHOW_COMMAND(file, db_show_file)
3679 db_printf("usage: show file <addr>\n");
3682 fp = (struct file *)addr;
3683 db_print_file(fp, 1);
3686 DB_SHOW_COMMAND(files, db_show_files)
3688 struct filedesc *fdp;
3695 FOREACH_PROC_IN_SYSTEM(p) {
3696 if (p->p_state == PRS_NEW)
3698 if ((fdp = p->p_fd) == NULL)
3700 for (n = 0; n < fdp->fd_nfiles; ++n) {
3701 if ((fp = fdp->fd_ofiles[n]) == NULL)
3703 db_print_file(fp, header);
3710 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3711 &maxfilesperproc, 0, "Maximum files allowed open per process");
3713 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3714 &maxfiles, 0, "Maximum number of files");
3716 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3717 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3721 filelistinit(void *dummy)
3724 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3725 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3726 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3727 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3729 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3731 /*-------------------------------------------------------------------*/
3734 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3735 int flags, struct thread *td)
3742 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3750 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3758 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3766 badfo_kqfilter(struct file *fp, struct knote *kn)
3773 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3781 badfo_close(struct file *fp, struct thread *td)
3788 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3796 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3803 struct fileops badfileops = {
3804 .fo_read = badfo_readwrite,
3805 .fo_write = badfo_readwrite,
3806 .fo_truncate = badfo_truncate,
3807 .fo_ioctl = badfo_ioctl,
3808 .fo_poll = badfo_poll,
3809 .fo_kqfilter = badfo_kqfilter,
3810 .fo_stat = badfo_stat,
3811 .fo_close = badfo_close,
3812 .fo_chmod = badfo_chmod,
3813 .fo_chown = badfo_chown,
3817 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3825 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3832 /*-------------------------------------------------------------------*/
3835 * File Descriptor pseudo-device driver (/dev/fd/).
3837 * Opening minor device N dup()s the file (if any) connected to file
3838 * descriptor N belonging to the calling process. Note that this driver
3839 * consists of only the ``open()'' routine, because all subsequent
3840 * references to this file will be direct to the other driver.
3842 * XXX: we could give this one a cloning event handler if necessary.
3847 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3851 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3852 * the file descriptor being sought for duplication. The error
3853 * return ensures that the vnode for this device will be released
3854 * by vn_open. Open will detect this special error and take the
3855 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3856 * will simply report the error.
3858 td->td_dupfd = dev2unit(dev);
3862 static struct cdevsw fildesc_cdevsw = {
3863 .d_version = D_VERSION,
3869 fildesc_drvinit(void *unused)
3873 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3874 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3875 make_dev_alias(dev, "stdin");
3876 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3877 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3878 make_dev_alias(dev, "stdout");
3879 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3880 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3881 make_dev_alias(dev, "stderr");
3884 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);