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 */
117 static int do_dup(struct thread *td, int flags, int old, int new,
119 static int fd_first_free(struct filedesc *, int, int);
120 static int fd_last_used(struct filedesc *, int, int);
121 static void fdgrowtable(struct filedesc *, int);
122 static void fdunused(struct filedesc *fdp, int fd);
123 static void fdused(struct filedesc *fdp, int fd);
124 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
125 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
126 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
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_shm_info(struct file *fp, struct kinfo_file *kif);
133 * A process is initially started out with NDFILE descriptors stored within
134 * this structure, selected to be enough for typical applications based on
135 * the historical limit of 20 open files (and the usage of descriptors by
136 * shells). If these descriptors are exhausted, a larger descriptor table
137 * may be allocated, up to a process' resource limit; the internal arrays
141 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
142 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
143 #define NDSLOT(x) ((x) / NDENTRIES)
144 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
145 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
148 * Storage required per open file descriptor.
150 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
153 * Storage to hold unused ofiles that need to be reclaimed.
156 struct file **ft_table;
157 SLIST_ENTRY(freetable) ft_next;
161 * Basic allocation of descriptors:
162 * one of the above, plus arrays for NDFILE descriptors.
165 struct filedesc fd_fd;
167 * ofiles which need to be reclaimed on free.
169 SLIST_HEAD(,freetable) fd_free;
171 * These arrays are used when the number of open files is
172 * <= NDFILE, and are then pointed to by the pointers above.
174 struct file *fd_dfiles[NDFILE];
175 char fd_dfileflags[NDFILE];
176 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
180 * Descriptor management.
182 volatile int openfiles; /* actual number of open files */
183 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
184 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
186 /* A mutex to protect the association between a proc and filedesc. */
187 static struct mtx fdesc_mtx;
190 * Find the first zero bit in the given bitmap, starting at low and not
191 * exceeding size - 1.
194 fd_first_free(struct filedesc *fdp, int low, int size)
196 NDSLOTTYPE *map = fdp->fd_map;
204 if (low % NDENTRIES) {
205 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
206 if ((mask &= ~map[off]) != 0UL)
207 return (off * NDENTRIES + ffsl(mask) - 1);
210 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
211 if (map[off] != ~0UL)
212 return (off * NDENTRIES + ffsl(~map[off]) - 1);
217 * Find the highest non-zero bit in the given bitmap, starting at low and
218 * not exceeding size - 1.
221 fd_last_used(struct filedesc *fdp, int low, int size)
223 NDSLOTTYPE *map = fdp->fd_map;
231 if (size % NDENTRIES) {
232 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
233 if ((mask &= map[off]) != 0)
234 return (off * NDENTRIES + flsl(mask) - 1);
237 for (minoff = NDSLOT(low); off >= minoff; --off)
239 return (off * NDENTRIES + flsl(map[off]) - 1);
244 fdisused(struct filedesc *fdp, int fd)
246 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
247 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
248 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
252 * Mark a file descriptor as used.
255 fdused(struct filedesc *fdp, int fd)
258 FILEDESC_XLOCK_ASSERT(fdp);
259 KASSERT(!fdisused(fdp, fd),
260 ("fd already used"));
262 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
263 if (fd > fdp->fd_lastfile)
264 fdp->fd_lastfile = fd;
265 if (fd == fdp->fd_freefile)
266 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
270 * Mark a file descriptor as unused.
273 fdunused(struct filedesc *fdp, int fd)
276 FILEDESC_XLOCK_ASSERT(fdp);
277 KASSERT(fdisused(fdp, fd),
278 ("fd is already unused"));
279 KASSERT(fdp->fd_ofiles[fd] == NULL,
280 ("fd is still in use"));
282 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
283 if (fd < fdp->fd_freefile)
284 fdp->fd_freefile = fd;
285 if (fd == fdp->fd_lastfile)
286 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
290 * System calls on descriptors.
292 #ifndef _SYS_SYSPROTO_H_
293 struct getdtablesize_args {
299 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
301 struct proc *p = td->td_proc;
306 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
307 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
309 if (lim < td->td_retval[0])
310 td->td_retval[0] = lim;
315 * Duplicate a file descriptor to a particular value.
317 * Note: keep in mind that a potential race condition exists when closing
318 * descriptors from a shared descriptor table (via rfork).
320 #ifndef _SYS_SYSPROTO_H_
328 sys_dup2(struct thread *td, struct dup2_args *uap)
331 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
336 * Duplicate a file descriptor.
338 #ifndef _SYS_SYSPROTO_H_
345 sys_dup(struct thread *td, struct dup_args *uap)
348 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
352 * The file control system call.
354 #ifndef _SYS_SYSPROTO_H_
363 sys_fcntl(struct thread *td, struct fcntl_args *uap)
378 * Convert old flock structure to new.
380 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
381 fl.l_start = ofl.l_start;
382 fl.l_len = ofl.l_len;
383 fl.l_pid = ofl.l_pid;
384 fl.l_type = ofl.l_type;
385 fl.l_whence = ofl.l_whence;
405 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
414 error = kern_fcntl(td, uap->fd, cmd, arg);
417 if (uap->cmd == F_OGETLK) {
418 ofl.l_start = fl.l_start;
419 ofl.l_len = fl.l_len;
420 ofl.l_pid = fl.l_pid;
421 ofl.l_type = fl.l_type;
422 ofl.l_whence = fl.l_whence;
423 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
424 } else if (uap->cmd == F_GETLK) {
425 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
430 static inline struct file *
431 fdtofp(int fd, struct filedesc *fdp)
435 FILEDESC_LOCK_ASSERT(fdp);
436 if ((unsigned)fd >= fdp->fd_nfiles ||
437 (fp = fdp->fd_ofiles[fd]) == NULL)
443 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
446 *fpp = fdtofp(fd, fdp);
451 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
452 int err = cap_funwrap(*fpp, rights, fpp);
458 #endif /* CAPABILITIES */
463 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
465 struct filedesc *fdp;
485 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
490 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
495 if ((fp = fdtofp(fd, fdp)) == NULL) {
496 FILEDESC_SUNLOCK(fdp);
500 pop = &fdp->fd_ofileflags[fd];
501 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
502 FILEDESC_SUNLOCK(fdp);
507 if ((fp = fdtofp(fd, fdp)) == NULL) {
508 FILEDESC_XUNLOCK(fdp);
512 pop = &fdp->fd_ofileflags[fd];
513 *pop = (*pop &~ UF_EXCLOSE) |
514 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
515 FILEDESC_XUNLOCK(fdp);
520 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
522 FILEDESC_SUNLOCK(fdp);
525 td->td_retval[0] = OFLAGS(fp->f_flag);
526 FILEDESC_SUNLOCK(fdp);
531 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
533 FILEDESC_SUNLOCK(fdp);
537 FILEDESC_SUNLOCK(fdp);
539 tmp = flg = fp->f_flag;
541 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
542 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
543 tmp = fp->f_flag & FNONBLOCK;
544 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
549 tmp = fp->f_flag & FASYNC;
550 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
555 atomic_clear_int(&fp->f_flag, FNONBLOCK);
557 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
563 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
565 FILEDESC_SUNLOCK(fdp);
569 FILEDESC_SUNLOCK(fdp);
570 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
572 td->td_retval[0] = tmp;
578 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
580 FILEDESC_SUNLOCK(fdp);
584 FILEDESC_SUNLOCK(fdp);
586 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
591 error = priv_check(td, PRIV_NFS_LOCKD);
599 /* FALLTHROUGH F_SETLK */
604 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
606 FILEDESC_SUNLOCK(fdp);
609 if (fp->f_type != DTYPE_VNODE) {
610 FILEDESC_SUNLOCK(fdp);
614 flp = (struct flock *)arg;
615 if (flp->l_whence == SEEK_CUR) {
616 if (fp->f_offset < 0 ||
618 fp->f_offset > OFF_MAX - flp->l_start)) {
619 FILEDESC_SUNLOCK(fdp);
623 flp->l_start += fp->f_offset;
627 * VOP_ADVLOCK() may block.
630 FILEDESC_SUNLOCK(fdp);
632 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
633 switch (flp->l_type) {
635 if ((fp->f_flag & FREAD) == 0) {
639 PROC_LOCK(p->p_leader);
640 p->p_leader->p_flag |= P_ADVLOCK;
641 PROC_UNLOCK(p->p_leader);
642 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
646 if ((fp->f_flag & FWRITE) == 0) {
650 PROC_LOCK(p->p_leader);
651 p->p_leader->p_flag |= P_ADVLOCK;
652 PROC_UNLOCK(p->p_leader);
653 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
657 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
662 * Temporary api for testing remote lock
665 if (flg != F_REMOTE) {
669 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
670 F_UNLCKSYS, flp, flg);
676 VFS_UNLOCK_GIANT(vfslocked);
678 /* Check for race with close */
680 if ((unsigned) fd >= fdp->fd_nfiles ||
681 fp != fdp->fd_ofiles[fd]) {
682 FILEDESC_SUNLOCK(fdp);
683 flp->l_whence = SEEK_SET;
686 flp->l_type = F_UNLCK;
687 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
688 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
689 F_UNLCK, flp, F_POSIX);
690 VFS_UNLOCK_GIANT(vfslocked);
693 FILEDESC_SUNLOCK(fdp);
699 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
701 FILEDESC_SUNLOCK(fdp);
704 if (fp->f_type != DTYPE_VNODE) {
705 FILEDESC_SUNLOCK(fdp);
709 flp = (struct flock *)arg;
710 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
711 flp->l_type != F_UNLCK) {
712 FILEDESC_SUNLOCK(fdp);
716 if (flp->l_whence == SEEK_CUR) {
717 if ((flp->l_start > 0 &&
718 fp->f_offset > OFF_MAX - flp->l_start) ||
720 fp->f_offset < OFF_MIN - flp->l_start)) {
721 FILEDESC_SUNLOCK(fdp);
725 flp->l_start += fp->f_offset;
728 * VOP_ADVLOCK() may block.
731 FILEDESC_SUNLOCK(fdp);
733 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
734 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
736 VFS_UNLOCK_GIANT(vfslocked);
742 arg = arg ? 128 * 1024: 0;
746 if ((fp = fdtofp(fd, fdp)) == NULL) {
747 FILEDESC_SUNLOCK(fdp);
751 if (fp->f_type != DTYPE_VNODE) {
752 FILEDESC_SUNLOCK(fdp);
757 FILEDESC_SUNLOCK(fdp);
760 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
761 error = vn_lock(vp, LK_SHARED);
763 goto readahead_vnlock_fail;
764 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
766 fp->f_seqcount = (arg + bsize - 1) / bsize;
768 new = old = fp->f_flag;
770 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
771 readahead_vnlock_fail:
772 VFS_UNLOCK_GIANT(vfslocked);
776 new = old = fp->f_flag;
778 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
787 VFS_UNLOCK_GIANT(vfslocked);
792 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
795 do_dup(struct thread *td, int flags, int old, int new,
798 struct filedesc *fdp;
802 int error, holdleaders, maxfd;
808 * Verify we have a valid descriptor to dup from and possibly to
809 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
810 * return EINVAL when the new descriptor is out of bounds.
815 return (flags & DUP_FCNTL ? EINVAL : EBADF);
817 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
820 return (flags & DUP_FCNTL ? EINVAL : EBADF);
823 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
824 FILEDESC_XUNLOCK(fdp);
827 if (flags & DUP_FIXED && old == new) {
829 FILEDESC_XUNLOCK(fdp);
832 fp = fdp->fd_ofiles[old];
836 * If the caller specified a file descriptor, make sure the file
837 * table is large enough to hold it, and grab it. Otherwise, just
838 * allocate a new descriptor the usual way. Since the filedesc
839 * lock may be temporarily dropped in the process, we have to look
842 if (flags & DUP_FIXED) {
843 if (new >= fdp->fd_nfiles) {
845 * The resource limits are here instead of e.g. fdalloc(),
846 * because the file descriptor table may be shared between
847 * processes, so we can't really use racct_add()/racct_sub().
848 * Instead of counting the number of actually allocated
849 * descriptors, just put the limit on the size of the file
854 error = racct_set(p, RACCT_NOFILE, new + 1);
857 FILEDESC_XUNLOCK(fdp);
862 fdgrowtable(fdp, new + 1);
864 if (fdp->fd_ofiles[new] == NULL)
867 if ((error = fdalloc(td, new, &new)) != 0) {
868 FILEDESC_XUNLOCK(fdp);
875 * If the old file changed out from under us then treat it as a
876 * bad file descriptor. Userland should do its own locking to
879 if (fdp->fd_ofiles[old] != fp) {
880 /* we've allocated a descriptor which we won't use */
881 if (fdp->fd_ofiles[new] == NULL)
883 FILEDESC_XUNLOCK(fdp);
888 ("new fd is same as old"));
891 * Save info on the descriptor being overwritten. We cannot close
892 * it without introducing an ownership race for the slot, since we
893 * need to drop the filedesc lock to call closef().
895 * XXX this duplicates parts of close().
897 delfp = fdp->fd_ofiles[new];
900 if (td->td_proc->p_fdtol != NULL) {
902 * Ask fdfree() to sleep to ensure that all relevant
903 * process leaders can be traversed in closef().
905 fdp->fd_holdleaderscount++;
911 * Duplicate the source descriptor
913 fdp->fd_ofiles[new] = fp;
914 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
915 if (new > fdp->fd_lastfile)
916 fdp->fd_lastfile = new;
920 * If we dup'd over a valid file, we now own the reference to it
921 * and must dispose of it using closef() semantics (as if a
922 * close() were performed on it).
924 * XXX this duplicates parts of close().
927 knote_fdclose(td, new);
928 if (delfp->f_type == DTYPE_MQUEUE)
929 mq_fdclose(td, new, delfp);
930 FILEDESC_XUNLOCK(fdp);
931 (void) closef(delfp, td);
934 fdp->fd_holdleaderscount--;
935 if (fdp->fd_holdleaderscount == 0 &&
936 fdp->fd_holdleaderswakeup != 0) {
937 fdp->fd_holdleaderswakeup = 0;
938 wakeup(&fdp->fd_holdleaderscount);
940 FILEDESC_XUNLOCK(fdp);
943 FILEDESC_XUNLOCK(fdp);
949 * If sigio is on the list associated with a process or process group,
950 * disable signalling from the device, remove sigio from the list and
954 funsetown(struct sigio **sigiop)
964 *(sigio->sio_myref) = NULL;
965 if ((sigio)->sio_pgid < 0) {
966 struct pgrp *pg = (sigio)->sio_pgrp;
968 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
972 struct proc *p = (sigio)->sio_proc;
974 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
979 crfree(sigio->sio_ucred);
980 free(sigio, M_SIGIO);
984 * Free a list of sigio structures.
985 * We only need to lock the SIGIO_LOCK because we have made ourselves
986 * inaccessible to callers of fsetown and therefore do not need to lock
987 * the proc or pgrp struct for the list manipulation.
990 funsetownlst(struct sigiolst *sigiolst)
996 sigio = SLIST_FIRST(sigiolst);
1003 * Every entry of the list should belong
1004 * to a single proc or pgrp.
1006 if (sigio->sio_pgid < 0) {
1007 pg = sigio->sio_pgrp;
1008 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1009 } else /* if (sigio->sio_pgid > 0) */ {
1010 p = sigio->sio_proc;
1011 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1015 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1016 *(sigio->sio_myref) = NULL;
1018 KASSERT(sigio->sio_pgid < 0,
1019 ("Proc sigio in pgrp sigio list"));
1020 KASSERT(sigio->sio_pgrp == pg,
1021 ("Bogus pgrp in sigio list"));
1023 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1026 } else /* if (p != NULL) */ {
1027 KASSERT(sigio->sio_pgid > 0,
1028 ("Pgrp sigio in proc sigio list"));
1029 KASSERT(sigio->sio_proc == p,
1030 ("Bogus proc in sigio list"));
1032 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1037 crfree(sigio->sio_ucred);
1038 free(sigio, M_SIGIO);
1045 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1047 * After permission checking, add a sigio structure to the sigio list for
1048 * the process or process group.
1051 fsetown(pid_t pgid, struct sigio **sigiop)
1055 struct sigio *sigio;
1065 /* Allocate and fill in the new sigio out of locks. */
1066 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1067 sigio->sio_pgid = pgid;
1068 sigio->sio_ucred = crhold(curthread->td_ucred);
1069 sigio->sio_myref = sigiop;
1071 sx_slock(&proctree_lock);
1080 * Policy - Don't allow a process to FSETOWN a process
1081 * in another session.
1083 * Remove this test to allow maximum flexibility or
1084 * restrict FSETOWN to the current process or process
1085 * group for maximum safety.
1088 if (proc->p_session != curthread->td_proc->p_session) {
1094 } else /* if (pgid < 0) */ {
1095 pgrp = pgfind(-pgid);
1103 * Policy - Don't allow a process to FSETOWN a process
1104 * in another session.
1106 * Remove this test to allow maximum flexibility or
1107 * restrict FSETOWN to the current process or process
1108 * group for maximum safety.
1110 if (pgrp->pg_session != curthread->td_proc->p_session) {
1121 * Since funsetownlst() is called without the proctree
1122 * locked, we need to check for P_WEXIT.
1123 * XXX: is ESRCH correct?
1125 if ((proc->p_flag & P_WEXIT) != 0) {
1130 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1131 sigio->sio_proc = proc;
1135 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1136 sigio->sio_pgrp = pgrp;
1139 sx_sunlock(&proctree_lock);
1146 sx_sunlock(&proctree_lock);
1147 crfree(sigio->sio_ucred);
1148 free(sigio, M_SIGIO);
1153 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1157 struct sigio **sigiop;
1162 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1168 * Close a file descriptor.
1170 #ifndef _SYS_SYSPROTO_H_
1179 struct close_args *uap;
1182 return (kern_close(td, uap->fd));
1190 struct filedesc *fdp;
1191 struct file *fp, *fp_object;
1197 fdp = td->td_proc->p_fd;
1199 AUDIT_SYSCLOSE(td, fd);
1201 FILEDESC_XLOCK(fdp);
1202 if ((unsigned)fd >= fdp->fd_nfiles ||
1203 (fp = fdp->fd_ofiles[fd]) == NULL) {
1204 FILEDESC_XUNLOCK(fdp);
1207 fdp->fd_ofiles[fd] = NULL;
1208 fdp->fd_ofileflags[fd] = 0;
1210 if (td->td_proc->p_fdtol != NULL) {
1212 * Ask fdfree() to sleep to ensure that all relevant
1213 * process leaders can be traversed in closef().
1215 fdp->fd_holdleaderscount++;
1220 * We now hold the fp reference that used to be owned by the
1221 * descriptor array. We have to unlock the FILEDESC *AFTER*
1222 * knote_fdclose to prevent a race of the fd getting opened, a knote
1223 * added, and deleteing a knote for the new fd.
1225 knote_fdclose(td, fd);
1228 * When we're closing an fd with a capability, we need to notify
1229 * mqueue if the underlying object is of type mqueue.
1231 (void)cap_funwrap(fp, 0, &fp_object);
1232 if (fp_object->f_type == DTYPE_MQUEUE)
1233 mq_fdclose(td, fd, fp_object);
1234 FILEDESC_XUNLOCK(fdp);
1236 error = closef(fp, td);
1238 FILEDESC_XLOCK(fdp);
1239 fdp->fd_holdleaderscount--;
1240 if (fdp->fd_holdleaderscount == 0 &&
1241 fdp->fd_holdleaderswakeup != 0) {
1242 fdp->fd_holdleaderswakeup = 0;
1243 wakeup(&fdp->fd_holdleaderscount);
1245 FILEDESC_XUNLOCK(fdp);
1251 * Close open file descriptors.
1253 #ifndef _SYS_SYSPROTO_H_
1254 struct closefrom_args {
1260 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1262 struct filedesc *fdp;
1265 fdp = td->td_proc->p_fd;
1266 AUDIT_ARG_FD(uap->lowfd);
1269 * Treat negative starting file descriptor values identical to
1270 * closefrom(0) which closes all files.
1274 FILEDESC_SLOCK(fdp);
1275 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1276 if (fdp->fd_ofiles[fd] != NULL) {
1277 FILEDESC_SUNLOCK(fdp);
1278 (void)kern_close(td, fd);
1279 FILEDESC_SLOCK(fdp);
1282 FILEDESC_SUNLOCK(fdp);
1286 #if defined(COMPAT_43)
1288 * Return status information about a file descriptor.
1290 #ifndef _SYS_SYSPROTO_H_
1291 struct ofstat_args {
1298 ofstat(struct thread *td, struct ofstat_args *uap)
1304 error = kern_fstat(td, uap->fd, &ub);
1307 error = copyout(&oub, uap->sb, sizeof(oub));
1311 #endif /* COMPAT_43 */
1314 * Return status information about a file descriptor.
1316 #ifndef _SYS_SYSPROTO_H_
1324 sys_fstat(struct thread *td, struct fstat_args *uap)
1329 error = kern_fstat(td, uap->fd, &ub);
1331 error = copyout(&ub, uap->sb, sizeof(ub));
1336 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1343 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1346 AUDIT_ARG_FILE(td->td_proc, fp);
1348 error = fo_stat(fp, sbp, td->td_ucred, td);
1351 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1358 * Return status information about a file descriptor.
1360 #ifndef _SYS_SYSPROTO_H_
1361 struct nfstat_args {
1368 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1374 error = kern_fstat(td, uap->fd, &ub);
1376 cvtnstat(&ub, &nub);
1377 error = copyout(&nub, uap->sb, sizeof(nub));
1383 * Return pathconf information about a file descriptor.
1385 #ifndef _SYS_SYSPROTO_H_
1386 struct fpathconf_args {
1393 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1399 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1402 /* If asynchronous I/O is available, it works for all descriptors. */
1403 if (uap->name == _PC_ASYNC_IO) {
1404 td->td_retval[0] = async_io_version;
1410 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1411 vn_lock(vp, LK_SHARED | LK_RETRY);
1412 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1414 VFS_UNLOCK_GIANT(vfslocked);
1415 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1416 if (uap->name != _PC_PIPE_BUF) {
1419 td->td_retval[0] = PIPE_BUF;
1431 * Grow the file table to accomodate (at least) nfd descriptors. This may
1432 * block and drop the filedesc lock, but it will reacquire it before
1436 fdgrowtable(struct filedesc *fdp, int nfd)
1438 struct filedesc0 *fdp0;
1439 struct freetable *fo;
1440 struct file **ntable;
1441 struct file **otable;
1443 int nnfiles, onfiles;
1446 FILEDESC_XLOCK_ASSERT(fdp);
1448 KASSERT(fdp->fd_nfiles > 0,
1449 ("zero-length file table"));
1451 /* compute the size of the new table */
1452 onfiles = fdp->fd_nfiles;
1453 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1454 if (nnfiles <= onfiles)
1455 /* the table is already large enough */
1458 /* allocate a new table and (if required) new bitmaps */
1459 FILEDESC_XUNLOCK(fdp);
1460 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1461 M_FILEDESC, M_ZERO | M_WAITOK);
1462 nfileflags = (char *)&ntable[nnfiles];
1463 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1464 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1465 M_FILEDESC, M_ZERO | M_WAITOK);
1468 FILEDESC_XLOCK(fdp);
1471 * We now have new tables ready to go. Since we dropped the
1472 * filedesc lock to call malloc(), watch out for a race.
1474 onfiles = fdp->fd_nfiles;
1475 if (onfiles >= nnfiles) {
1476 /* we lost the race, but that's OK */
1477 free(ntable, M_FILEDESC);
1479 free(nmap, M_FILEDESC);
1482 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1483 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1484 otable = fdp->fd_ofiles;
1485 fdp->fd_ofileflags = nfileflags;
1486 fdp->fd_ofiles = ntable;
1488 * We must preserve ofiles until the process exits because we can't
1489 * be certain that no threads have references to the old table via
1492 if (onfiles > NDFILE) {
1493 fo = (struct freetable *)&otable[onfiles];
1494 fdp0 = (struct filedesc0 *)fdp;
1495 fo->ft_table = otable;
1496 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1498 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1499 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1500 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1501 free(fdp->fd_map, M_FILEDESC);
1504 fdp->fd_nfiles = nnfiles;
1508 * Allocate a file descriptor for the process.
1511 fdalloc(struct thread *td, int minfd, int *result)
1513 struct proc *p = td->td_proc;
1514 struct filedesc *fdp = p->p_fd;
1520 FILEDESC_XLOCK_ASSERT(fdp);
1522 if (fdp->fd_freefile > minfd)
1523 minfd = fdp->fd_freefile;
1526 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1530 * Search the bitmap for a free descriptor. If none is found, try
1531 * to grow the file table. Keep at it until we either get a file
1532 * descriptor or run into process or system limits; fdgrowtable()
1533 * may drop the filedesc lock, so we're in a race.
1536 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1539 if (fd < fdp->fd_nfiles)
1543 error = racct_set(p, RACCT_NOFILE, min(fdp->fd_nfiles * 2, maxfd));
1548 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1552 * Perform some sanity checks, then mark the file descriptor as
1553 * used and return it to the caller.
1555 KASSERT(!fdisused(fdp, fd),
1556 ("fd_first_free() returned non-free descriptor"));
1557 KASSERT(fdp->fd_ofiles[fd] == NULL,
1558 ("free descriptor isn't"));
1559 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1566 * Check to see whether n user file descriptors are available to the process
1570 fdavail(struct thread *td, int n)
1572 struct proc *p = td->td_proc;
1573 struct filedesc *fdp = td->td_proc->p_fd;
1577 FILEDESC_LOCK_ASSERT(fdp);
1580 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1581 * call racct_add() from there instead of dealing with containers
1585 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1587 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1589 last = min(fdp->fd_nfiles, lim);
1590 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1591 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1592 if (*fpp == NULL && --n <= 0)
1599 * Create a new open file structure and allocate a file decriptor for the
1600 * process that refers to it. We add one reference to the file for the
1601 * descriptor table and one reference for resultfp. This is to prevent us
1602 * being preempted and the entry in the descriptor table closed after we
1603 * release the FILEDESC lock.
1606 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1611 error = falloc_noinstall(td, &fp);
1613 return (error); /* no reference held on error */
1615 error = finstall(td, fp, &fd, flags);
1617 fdrop(fp, td); /* one reference (fp only) */
1621 if (resultfp != NULL)
1622 *resultfp = fp; /* copy out result */
1624 fdrop(fp, td); /* release local reference */
1626 if (resultfd != NULL)
1633 * Create a new open file structure without allocating a file descriptor.
1636 falloc_noinstall(struct thread *td, struct file **resultfp)
1639 int maxuserfiles = maxfiles - (maxfiles / 20);
1640 static struct timeval lastfail;
1643 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1645 if ((openfiles >= maxuserfiles &&
1646 priv_check(td, PRIV_MAXFILES) != 0) ||
1647 openfiles >= maxfiles) {
1648 if (ppsratecheck(&lastfail, &curfail, 1)) {
1649 printf("kern.maxfiles limit exceeded by uid %i, "
1650 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1654 atomic_add_int(&openfiles, 1);
1655 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1656 refcount_init(&fp->f_count, 1);
1657 fp->f_cred = crhold(td->td_ucred);
1658 fp->f_ops = &badfileops;
1666 * Install a file in a file descriptor table.
1669 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1671 struct filedesc *fdp = td->td_proc->p_fd;
1674 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1675 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1677 FILEDESC_XLOCK(fdp);
1678 if ((error = fdalloc(td, 0, fd))) {
1679 FILEDESC_XUNLOCK(fdp);
1683 fdp->fd_ofiles[*fd] = fp;
1684 if ((flags & O_CLOEXEC) != 0)
1685 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1686 FILEDESC_XUNLOCK(fdp);
1691 * Build a new filedesc structure from another.
1692 * Copy the current, root, and jail root vnode references.
1695 fdinit(struct filedesc *fdp)
1697 struct filedesc0 *newfdp;
1699 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1700 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1702 FILEDESC_XLOCK(fdp);
1703 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1704 if (newfdp->fd_fd.fd_cdir)
1705 VREF(newfdp->fd_fd.fd_cdir);
1706 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1707 if (newfdp->fd_fd.fd_rdir)
1708 VREF(newfdp->fd_fd.fd_rdir);
1709 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1710 if (newfdp->fd_fd.fd_jdir)
1711 VREF(newfdp->fd_fd.fd_jdir);
1712 FILEDESC_XUNLOCK(fdp);
1715 /* Create the file descriptor table. */
1716 newfdp->fd_fd.fd_refcnt = 1;
1717 newfdp->fd_fd.fd_holdcnt = 1;
1718 newfdp->fd_fd.fd_cmask = CMASK;
1719 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1720 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1721 newfdp->fd_fd.fd_nfiles = NDFILE;
1722 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1723 newfdp->fd_fd.fd_lastfile = -1;
1724 return (&newfdp->fd_fd);
1727 static struct filedesc *
1728 fdhold(struct proc *p)
1730 struct filedesc *fdp;
1732 mtx_lock(&fdesc_mtx);
1736 mtx_unlock(&fdesc_mtx);
1741 fddrop(struct filedesc *fdp)
1743 struct filedesc0 *fdp0;
1744 struct freetable *ft;
1747 mtx_lock(&fdesc_mtx);
1748 i = --fdp->fd_holdcnt;
1749 mtx_unlock(&fdesc_mtx);
1753 FILEDESC_LOCK_DESTROY(fdp);
1754 fdp0 = (struct filedesc0 *)fdp;
1755 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1756 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1757 free(ft->ft_table, M_FILEDESC);
1759 free(fdp, M_FILEDESC);
1763 * Share a filedesc structure.
1766 fdshare(struct filedesc *fdp)
1769 FILEDESC_XLOCK(fdp);
1771 FILEDESC_XUNLOCK(fdp);
1776 * Unshare a filedesc structure, if necessary by making a copy
1779 fdunshare(struct proc *p, struct thread *td)
1782 FILEDESC_XLOCK(p->p_fd);
1783 if (p->p_fd->fd_refcnt > 1) {
1784 struct filedesc *tmp;
1786 FILEDESC_XUNLOCK(p->p_fd);
1787 tmp = fdcopy(p->p_fd);
1791 FILEDESC_XUNLOCK(p->p_fd);
1795 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1796 * this is to ease callers, not catch errors.
1799 fdcopy(struct filedesc *fdp)
1801 struct filedesc *newfdp;
1804 /* Certain daemons might not have file descriptors. */
1808 newfdp = fdinit(fdp);
1809 FILEDESC_SLOCK(fdp);
1810 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1811 FILEDESC_SUNLOCK(fdp);
1812 FILEDESC_XLOCK(newfdp);
1813 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1814 FILEDESC_XUNLOCK(newfdp);
1815 FILEDESC_SLOCK(fdp);
1817 /* copy all passable descriptors (i.e. not kqueue) */
1818 newfdp->fd_freefile = -1;
1819 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1820 if (fdisused(fdp, i) &&
1821 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1822 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1823 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1824 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1825 fhold(newfdp->fd_ofiles[i]);
1826 newfdp->fd_lastfile = i;
1828 if (newfdp->fd_freefile == -1)
1829 newfdp->fd_freefile = i;
1832 newfdp->fd_cmask = fdp->fd_cmask;
1833 FILEDESC_SUNLOCK(fdp);
1834 FILEDESC_XLOCK(newfdp);
1835 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1836 if (newfdp->fd_ofiles[i] != NULL)
1838 if (newfdp->fd_freefile == -1)
1839 newfdp->fd_freefile = i;
1840 FILEDESC_XUNLOCK(newfdp);
1845 * Release a filedesc structure.
1848 fdfree(struct thread *td)
1850 struct filedesc *fdp;
1853 struct filedesc_to_leader *fdtol;
1855 struct vnode *cdir, *jdir, *rdir, *vp;
1858 /* Certain daemons might not have file descriptors. */
1859 fdp = td->td_proc->p_fd;
1864 PROC_LOCK(td->td_proc);
1865 racct_set(td->td_proc, RACCT_NOFILE, 0);
1866 PROC_UNLOCK(td->td_proc);
1869 /* Check for special need to clear POSIX style locks */
1870 fdtol = td->td_proc->p_fdtol;
1871 if (fdtol != NULL) {
1872 FILEDESC_XLOCK(fdp);
1873 KASSERT(fdtol->fdl_refcount > 0,
1874 ("filedesc_to_refcount botch: fdl_refcount=%d",
1875 fdtol->fdl_refcount));
1876 if (fdtol->fdl_refcount == 1 &&
1877 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1878 for (i = 0, fpp = fdp->fd_ofiles;
1879 i <= fdp->fd_lastfile;
1882 (*fpp)->f_type != DTYPE_VNODE)
1886 FILEDESC_XUNLOCK(fdp);
1887 lf.l_whence = SEEK_SET;
1890 lf.l_type = F_UNLCK;
1892 locked = VFS_LOCK_GIANT(vp->v_mount);
1893 (void) VOP_ADVLOCK(vp,
1894 (caddr_t)td->td_proc->
1899 VFS_UNLOCK_GIANT(locked);
1900 FILEDESC_XLOCK(fdp);
1902 fpp = fdp->fd_ofiles + i;
1906 if (fdtol->fdl_refcount == 1) {
1907 if (fdp->fd_holdleaderscount > 0 &&
1908 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1910 * close() or do_dup() has cleared a reference
1911 * in a shared file descriptor table.
1913 fdp->fd_holdleaderswakeup = 1;
1914 sx_sleep(&fdp->fd_holdleaderscount,
1915 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1918 if (fdtol->fdl_holdcount > 0) {
1920 * Ensure that fdtol->fdl_leader remains
1921 * valid in closef().
1923 fdtol->fdl_wakeup = 1;
1924 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1929 fdtol->fdl_refcount--;
1930 if (fdtol->fdl_refcount == 0 &&
1931 fdtol->fdl_holdcount == 0) {
1932 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1933 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1936 td->td_proc->p_fdtol = NULL;
1937 FILEDESC_XUNLOCK(fdp);
1939 free(fdtol, M_FILEDESC_TO_LEADER);
1941 FILEDESC_XLOCK(fdp);
1942 i = --fdp->fd_refcnt;
1943 FILEDESC_XUNLOCK(fdp);
1947 fpp = fdp->fd_ofiles;
1948 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1950 FILEDESC_XLOCK(fdp);
1953 FILEDESC_XUNLOCK(fdp);
1954 (void) closef(fp, td);
1957 FILEDESC_XLOCK(fdp);
1959 /* XXX This should happen earlier. */
1960 mtx_lock(&fdesc_mtx);
1961 td->td_proc->p_fd = NULL;
1962 mtx_unlock(&fdesc_mtx);
1964 if (fdp->fd_nfiles > NDFILE)
1965 free(fdp->fd_ofiles, M_FILEDESC);
1966 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1967 free(fdp->fd_map, M_FILEDESC);
1971 cdir = fdp->fd_cdir;
1972 fdp->fd_cdir = NULL;
1973 rdir = fdp->fd_rdir;
1974 fdp->fd_rdir = NULL;
1975 jdir = fdp->fd_jdir;
1976 fdp->fd_jdir = NULL;
1977 FILEDESC_XUNLOCK(fdp);
1980 locked = VFS_LOCK_GIANT(cdir->v_mount);
1982 VFS_UNLOCK_GIANT(locked);
1985 locked = VFS_LOCK_GIANT(rdir->v_mount);
1987 VFS_UNLOCK_GIANT(locked);
1990 locked = VFS_LOCK_GIANT(jdir->v_mount);
1992 VFS_UNLOCK_GIANT(locked);
1999 * For setugid programs, we don't want to people to use that setugidness
2000 * to generate error messages which write to a file which otherwise would
2001 * otherwise be off-limits to the process. We check for filesystems where
2002 * the vnode can change out from under us after execve (like [lin]procfs).
2004 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2005 * sufficient. We also don't check for setugidness since we know we are.
2008 is_unsafe(struct file *fp)
2010 if (fp->f_type == DTYPE_VNODE) {
2011 struct vnode *vp = fp->f_vnode;
2013 if ((vp->v_vflag & VV_PROCDEP) != 0)
2020 * Make this setguid thing safe, if at all possible.
2023 setugidsafety(struct thread *td)
2025 struct filedesc *fdp;
2028 /* Certain daemons might not have file descriptors. */
2029 fdp = td->td_proc->p_fd;
2034 * Note: fdp->fd_ofiles may be reallocated out from under us while
2035 * we are blocked in a close. Be careful!
2037 FILEDESC_XLOCK(fdp);
2038 for (i = 0; i <= fdp->fd_lastfile; i++) {
2041 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2044 knote_fdclose(td, i);
2046 * NULL-out descriptor prior to close to avoid
2047 * a race while close blocks.
2049 fp = fdp->fd_ofiles[i];
2050 fdp->fd_ofiles[i] = NULL;
2051 fdp->fd_ofileflags[i] = 0;
2053 FILEDESC_XUNLOCK(fdp);
2054 (void) closef(fp, td);
2055 FILEDESC_XLOCK(fdp);
2058 FILEDESC_XUNLOCK(fdp);
2062 * If a specific file object occupies a specific file descriptor, close the
2063 * file descriptor entry and drop a reference on the file object. This is a
2064 * convenience function to handle a subsequent error in a function that calls
2065 * falloc() that handles the race that another thread might have closed the
2066 * file descriptor out from under the thread creating the file object.
2069 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2072 FILEDESC_XLOCK(fdp);
2073 if (fdp->fd_ofiles[idx] == fp) {
2074 fdp->fd_ofiles[idx] = NULL;
2076 FILEDESC_XUNLOCK(fdp);
2079 FILEDESC_XUNLOCK(fdp);
2083 * Close any files on exec?
2086 fdcloseexec(struct thread *td)
2088 struct filedesc *fdp;
2091 /* Certain daemons might not have file descriptors. */
2092 fdp = td->td_proc->p_fd;
2096 FILEDESC_XLOCK(fdp);
2099 * We cannot cache fd_ofiles or fd_ofileflags since operations
2100 * may block and rip them out from under us.
2102 for (i = 0; i <= fdp->fd_lastfile; i++) {
2103 if (fdp->fd_ofiles[i] != NULL &&
2104 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2105 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2108 knote_fdclose(td, i);
2110 * NULL-out descriptor prior to close to avoid
2111 * a race while close blocks.
2113 fp = fdp->fd_ofiles[i];
2114 fdp->fd_ofiles[i] = NULL;
2115 fdp->fd_ofileflags[i] = 0;
2117 if (fp->f_type == DTYPE_MQUEUE)
2118 mq_fdclose(td, i, fp);
2119 FILEDESC_XUNLOCK(fdp);
2120 (void) closef(fp, td);
2121 FILEDESC_XLOCK(fdp);
2124 FILEDESC_XUNLOCK(fdp);
2128 * It is unsafe for set[ug]id processes to be started with file
2129 * descriptors 0..2 closed, as these descriptors are given implicit
2130 * significance in the Standard C library. fdcheckstd() will create a
2131 * descriptor referencing /dev/null for each of stdin, stdout, and
2132 * stderr that is not already open.
2135 fdcheckstd(struct thread *td)
2137 struct filedesc *fdp;
2138 register_t retval, save;
2139 int i, error, devnull;
2141 fdp = td->td_proc->p_fd;
2144 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2147 for (i = 0; i < 3; i++) {
2148 if (fdp->fd_ofiles[i] != NULL)
2151 save = td->td_retval[0];
2152 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2154 devnull = td->td_retval[0];
2155 td->td_retval[0] = save;
2158 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2160 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2169 * Internal form of close. Decrement reference count on file structure.
2170 * Note: td may be NULL when closing a file that was being passed in a
2173 * XXXRW: Giant is not required for the caller, but often will be held; this
2174 * makes it moderately likely the Giant will be recursed in the VFS case.
2177 closef(struct file *fp, struct thread *td)
2181 struct filedesc_to_leader *fdtol;
2182 struct filedesc *fdp;
2183 struct file *fp_object;
2186 * POSIX record locking dictates that any close releases ALL
2187 * locks owned by this process. This is handled by setting
2188 * a flag in the unlock to free ONLY locks obeying POSIX
2189 * semantics, and not to free BSD-style file locks.
2190 * If the descriptor was in a message, POSIX-style locks
2191 * aren't passed with the descriptor, and the thread pointer
2192 * will be NULL. Callers should be careful only to pass a
2193 * NULL thread pointer when there really is no owning
2194 * context that might have locks, or the locks will be
2197 * If this is a capability, we do lock processing under the underlying
2198 * node, not the capability itself.
2200 (void)cap_funwrap(fp, 0, &fp_object);
2201 if ((fp_object->f_type == DTYPE_VNODE) && (td != NULL)) {
2204 vp = fp_object->f_vnode;
2205 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2206 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2207 lf.l_whence = SEEK_SET;
2210 lf.l_type = F_UNLCK;
2211 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2212 F_UNLCK, &lf, F_POSIX);
2214 fdtol = td->td_proc->p_fdtol;
2215 if (fdtol != NULL) {
2217 * Handle special case where file descriptor table is
2218 * shared between multiple process leaders.
2220 fdp = td->td_proc->p_fd;
2221 FILEDESC_XLOCK(fdp);
2222 for (fdtol = fdtol->fdl_next;
2223 fdtol != td->td_proc->p_fdtol;
2224 fdtol = fdtol->fdl_next) {
2225 if ((fdtol->fdl_leader->p_flag &
2228 fdtol->fdl_holdcount++;
2229 FILEDESC_XUNLOCK(fdp);
2230 lf.l_whence = SEEK_SET;
2233 lf.l_type = F_UNLCK;
2234 vp = fp_object->f_vnode;
2235 (void) VOP_ADVLOCK(vp,
2236 (caddr_t)fdtol->fdl_leader,
2237 F_UNLCK, &lf, F_POSIX);
2238 FILEDESC_XLOCK(fdp);
2239 fdtol->fdl_holdcount--;
2240 if (fdtol->fdl_holdcount == 0 &&
2241 fdtol->fdl_wakeup != 0) {
2242 fdtol->fdl_wakeup = 0;
2246 FILEDESC_XUNLOCK(fdp);
2248 VFS_UNLOCK_GIANT(vfslocked);
2250 return (fdrop(fp, td));
2254 * Initialize the file pointer with the specified properties.
2256 * The ops are set with release semantics to be certain that the flags, type,
2257 * and data are visible when ops is. This is to prevent ops methods from being
2258 * called with bad data.
2261 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2266 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2270 fget_unlocked(struct filedesc *fdp, int fd)
2275 if (fd < 0 || fd >= fdp->fd_nfiles)
2278 * Fetch the descriptor locklessly. We avoid fdrop() races by
2279 * never raising a refcount above 0. To accomplish this we have
2280 * to use a cmpset loop rather than an atomic_add. The descriptor
2281 * must be re-verified once we acquire a reference to be certain
2282 * that the identity is still correct and we did not lose a race
2283 * due to preemption.
2286 fp = fdp->fd_ofiles[fd];
2289 count = fp->f_count;
2293 * Use an acquire barrier to prevent caching of fd_ofiles
2294 * so it is refreshed for verification.
2296 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2298 if (fp == fdp->fd_ofiles[fd])
2300 fdrop(fp, curthread);
2307 * Extract the file pointer associated with the specified descriptor for the
2308 * current user process.
2310 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2313 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2314 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2315 * Otherwise, if the file is a capability, its rights will be checked against
2316 * the capability rights mask, and if successful, the object will be unwrapped.
2318 * If an error occured the non-zero error is returned and *fpp is set to
2319 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2320 * responsible for fdrop().
2322 #define FGET_GETCAP 0x00000001
2324 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2325 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2328 struct filedesc *fdp;
2331 struct file *fp_fromcap;
2336 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2338 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2340 if (fp->f_ops == &badfileops) {
2347 * If this is a capability, what rights does it have?
2349 if (haverightsp != NULL) {
2350 if (fp->f_type == DTYPE_CAPABILITY)
2351 *haverightsp = cap_rights(fp);
2353 *haverightsp = CAP_MASK_VALID;
2357 * If a capability has been requested, return the capability directly.
2358 * Otherwise, check capability rights, extract the underlying object,
2359 * and check its access flags.
2361 if (fget_flags & FGET_GETCAP) {
2362 if (fp->f_type != DTYPE_CAPABILITY) {
2367 if (maxprotp == NULL)
2368 error = cap_funwrap(fp, needrights, &fp_fromcap);
2370 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2378 * If we've unwrapped a file, drop the original capability
2379 * and hold the new descriptor. fp after this point refers to
2380 * the actual (unwrapped) object, not the capability.
2382 if (fp != fp_fromcap) {
2388 #else /* !CAPABILITIES */
2389 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2390 ("%s: saw capability", __func__));
2391 if (maxprotp != NULL)
2392 *maxprotp = VM_PROT_ALL;
2393 #endif /* CAPABILITIES */
2396 * FREAD and FWRITE failure return EBADF as per POSIX.
2398 * Only one flag, or 0, may be specified.
2400 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2401 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2410 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2413 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2417 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2421 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2425 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2428 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2432 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2435 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2439 * Unlike the other fget() calls, which accept and check capability rights
2440 * but never return capabilities, fgetcap() returns the capability but doesn't
2441 * check capability rights.
2444 fgetcap(struct thread *td, int fd, struct file **fpp)
2447 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2452 * Like fget() but loads the underlying vnode, or returns an error if the
2453 * descriptor does not represent a vnode. Note that pipes use vnodes but
2454 * never have VM objects. The returned vnode will be vref()'d.
2456 * XXX: what about the unused flags ?
2459 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2460 cap_rights_t *haverightsp, struct vnode **vpp)
2466 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2469 if (fp->f_vnode == NULL) {
2481 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2484 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2488 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2491 return (_fgetvp(td, fd, 0, need, have, vpp));
2495 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2498 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2503 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2507 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2512 * Like fget() but loads the underlying socket, or returns an error if the
2513 * descriptor does not represent a socket.
2515 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2518 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2519 * on their file descriptor reference to prevent the socket from being free'd
2523 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2532 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2534 if (fp->f_type != DTYPE_SOCKET) {
2539 *fflagp = fp->f_flag;
2550 * Drop the reference count on the socket and XXX release the SX lock in the
2551 * future. The last reference closes the socket.
2553 * Note: fputsock() is deprecated, see comment for fgetsock().
2556 fputsock(struct socket *so)
2561 CURVNET_SET(so->so_vnet);
2567 * Handle the last reference to a file being closed.
2569 * No special capability handling here, as the capability's fo_close will run
2570 * instead of the object here, and perform any necessary drop on the object.
2573 _fdrop(struct file *fp, struct thread *td)
2578 if (fp->f_count != 0)
2579 panic("fdrop: count %d", fp->f_count);
2580 if (fp->f_ops != &badfileops)
2581 error = fo_close(fp, td);
2582 atomic_subtract_int(&openfiles, 1);
2584 free(fp->f_advice, M_FADVISE);
2585 uma_zfree(file_zone, fp);
2591 * Apply an advisory lock on a file descriptor.
2593 * Just attempt to get a record lock of the requested type on the entire file
2594 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2596 #ifndef _SYS_SYSPROTO_H_
2604 sys_flock(struct thread *td, struct flock_args *uap)
2612 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2614 if (fp->f_type != DTYPE_VNODE) {
2616 return (EOPNOTSUPP);
2620 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2621 lf.l_whence = SEEK_SET;
2624 if (uap->how & LOCK_UN) {
2625 lf.l_type = F_UNLCK;
2626 atomic_clear_int(&fp->f_flag, FHASLOCK);
2627 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2630 if (uap->how & LOCK_EX)
2631 lf.l_type = F_WRLCK;
2632 else if (uap->how & LOCK_SH)
2633 lf.l_type = F_RDLCK;
2638 atomic_set_int(&fp->f_flag, FHASLOCK);
2639 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2640 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2643 VFS_UNLOCK_GIANT(vfslocked);
2647 * Duplicate the specified descriptor to a free descriptor.
2650 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2656 * If the to-be-dup'd fd number is greater than the allowed number
2657 * of file descriptors, or the fd to be dup'd has already been
2658 * closed, then reject.
2660 FILEDESC_XLOCK(fdp);
2661 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2662 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2663 FILEDESC_XUNLOCK(fdp);
2668 * There are two cases of interest here.
2670 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2672 * For ENXIO steal away the file structure from (dfd) and store it in
2673 * (indx). (dfd) is effectively closed by this operation.
2675 * Any other error code is just returned.
2680 * Check that the mode the file is being opened for is a
2681 * subset of the mode of the existing descriptor.
2683 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2684 FILEDESC_XUNLOCK(fdp);
2687 fp = fdp->fd_ofiles[indx];
2688 fdp->fd_ofiles[indx] = wfp;
2689 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2693 FILEDESC_XUNLOCK(fdp);
2696 * We now own the reference to fp that the ofiles[]
2697 * array used to own. Release it.
2704 * Steal away the file pointer from dfd and stuff it into indx.
2706 fp = fdp->fd_ofiles[indx];
2707 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2708 fdp->fd_ofiles[dfd] = NULL;
2709 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2710 fdp->fd_ofileflags[dfd] = 0;
2714 FILEDESC_XUNLOCK(fdp);
2717 * We now own the reference to fp that the ofiles[] array
2718 * used to own. Release it.
2725 FILEDESC_XUNLOCK(fdp);
2732 * Scan all active processes and prisons to see if any of them have a current
2733 * or root directory of `olddp'. If so, replace them with the new mount point.
2736 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2738 struct filedesc *fdp;
2743 if (vrefcnt(olddp) == 1)
2746 sx_slock(&allproc_lock);
2747 FOREACH_PROC_IN_SYSTEM(p) {
2751 FILEDESC_XLOCK(fdp);
2752 if (fdp->fd_cdir == olddp) {
2754 fdp->fd_cdir = newdp;
2757 if (fdp->fd_rdir == olddp) {
2759 fdp->fd_rdir = newdp;
2762 if (fdp->fd_jdir == olddp) {
2764 fdp->fd_jdir = newdp;
2767 FILEDESC_XUNLOCK(fdp);
2770 sx_sunlock(&allproc_lock);
2771 if (rootvnode == olddp) {
2776 mtx_lock(&prison0.pr_mtx);
2777 if (prison0.pr_root == olddp) {
2779 prison0.pr_root = newdp;
2782 mtx_unlock(&prison0.pr_mtx);
2783 sx_slock(&allprison_lock);
2784 TAILQ_FOREACH(pr, &allprison, pr_list) {
2785 mtx_lock(&pr->pr_mtx);
2786 if (pr->pr_root == olddp) {
2788 pr->pr_root = newdp;
2791 mtx_unlock(&pr->pr_mtx);
2793 sx_sunlock(&allprison_lock);
2798 struct filedesc_to_leader *
2799 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2801 struct filedesc_to_leader *fdtol;
2803 fdtol = malloc(sizeof(struct filedesc_to_leader),
2804 M_FILEDESC_TO_LEADER,
2806 fdtol->fdl_refcount = 1;
2807 fdtol->fdl_holdcount = 0;
2808 fdtol->fdl_wakeup = 0;
2809 fdtol->fdl_leader = leader;
2811 FILEDESC_XLOCK(fdp);
2812 fdtol->fdl_next = old->fdl_next;
2813 fdtol->fdl_prev = old;
2814 old->fdl_next = fdtol;
2815 fdtol->fdl_next->fdl_prev = fdtol;
2816 FILEDESC_XUNLOCK(fdp);
2818 fdtol->fdl_next = fdtol;
2819 fdtol->fdl_prev = fdtol;
2825 * Get file structures globally.
2828 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2831 struct filedesc *fdp;
2836 error = sysctl_wire_old_buffer(req, 0);
2839 if (req->oldptr == NULL) {
2841 sx_slock(&allproc_lock);
2842 FOREACH_PROC_IN_SYSTEM(p) {
2843 if (p->p_state == PRS_NEW)
2848 /* overestimates sparse tables. */
2849 if (fdp->fd_lastfile > 0)
2850 n += fdp->fd_lastfile;
2853 sx_sunlock(&allproc_lock);
2854 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2857 bzero(&xf, sizeof(xf));
2858 xf.xf_size = sizeof(xf);
2859 sx_slock(&allproc_lock);
2860 FOREACH_PROC_IN_SYSTEM(p) {
2862 if (p->p_state == PRS_NEW) {
2866 if (p_cansee(req->td, p) != 0) {
2870 xf.xf_pid = p->p_pid;
2871 xf.xf_uid = p->p_ucred->cr_uid;
2876 FILEDESC_SLOCK(fdp);
2877 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2878 if ((fp = fdp->fd_ofiles[n]) == NULL)
2882 xf.xf_data = fp->f_data;
2883 xf.xf_vnode = fp->f_vnode;
2884 xf.xf_type = fp->f_type;
2885 xf.xf_count = fp->f_count;
2887 xf.xf_offset = fp->f_offset;
2888 xf.xf_flag = fp->f_flag;
2889 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2893 FILEDESC_SUNLOCK(fdp);
2898 sx_sunlock(&allproc_lock);
2902 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2903 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2905 #ifdef KINFO_OFILE_SIZE
2906 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2909 #ifdef COMPAT_FREEBSD7
2911 export_vnode_for_osysctl(struct vnode *vp, int type,
2912 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2915 char *fullpath, *freepath;
2918 bzero(kif, sizeof(*kif));
2919 kif->kf_structsize = sizeof(*kif);
2923 kif->kf_type = KF_TYPE_VNODE;
2924 /* This function only handles directories. */
2925 if (vp->v_type != VDIR) {
2929 kif->kf_vnode_type = KF_VTYPE_VDIR;
2932 * This is not a true file descriptor, so we set a bogus refcount
2933 * and offset to indicate these fields should be ignored.
2935 kif->kf_ref_count = -1;
2936 kif->kf_offset = -1;
2940 FILEDESC_SUNLOCK(fdp);
2941 vn_fullpath(curthread, vp, &fullpath, &freepath);
2942 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2944 VFS_UNLOCK_GIANT(vfslocked);
2945 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2946 if (freepath != NULL)
2947 free(freepath, M_TEMP);
2948 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2949 FILEDESC_SLOCK(fdp);
2954 * Get per-process file descriptors for use by procstat(1), et al.
2957 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2959 char *fullpath, *freepath;
2960 struct kinfo_ofile *kif;
2961 struct filedesc *fdp;
2962 int error, i, *name;
2963 struct shmfd *shmfd;
2972 if ((p = pfind((pid_t)name[0])) == NULL)
2974 if ((error = p_candebug(curthread, p))) {
2982 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2983 FILEDESC_SLOCK(fdp);
2984 if (fdp->fd_cdir != NULL)
2985 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2987 if (fdp->fd_rdir != NULL)
2988 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2990 if (fdp->fd_jdir != NULL)
2991 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2993 for (i = 0; i < fdp->fd_nfiles; i++) {
2994 if ((fp = fdp->fd_ofiles[i]) == NULL)
2996 bzero(kif, sizeof(*kif));
2997 kif->kf_structsize = sizeof(*kif);
3006 * When reporting a capability, most fields will be from the
3007 * underlying object, but do mark as a capability. With
3008 * ofiledesc, we don't have a field to export the cap_rights_t,
3009 * but we do with the new filedesc.
3011 if (fp->f_type == DTYPE_CAPABILITY) {
3012 kif->kf_flags |= KF_FLAG_CAPABILITY;
3013 (void)cap_funwrap(fp, 0, &fp);
3016 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3017 ("sysctl_kern_proc_ofiledesc: saw capability"));
3019 switch (fp->f_type) {
3021 kif->kf_type = KF_TYPE_VNODE;
3026 kif->kf_type = KF_TYPE_SOCKET;
3031 kif->kf_type = KF_TYPE_PIPE;
3035 kif->kf_type = KF_TYPE_FIFO;
3040 kif->kf_type = KF_TYPE_KQUEUE;
3044 kif->kf_type = KF_TYPE_CRYPTO;
3048 kif->kf_type = KF_TYPE_MQUEUE;
3052 kif->kf_type = KF_TYPE_SHM;
3057 kif->kf_type = KF_TYPE_SEM;
3061 kif->kf_type = KF_TYPE_PTS;
3066 case DTYPE_PROCDESC:
3067 kif->kf_type = KF_TYPE_PROCDESC;
3072 kif->kf_type = KF_TYPE_UNKNOWN;
3075 kif->kf_ref_count = fp->f_count;
3076 if (fp->f_flag & FREAD)
3077 kif->kf_flags |= KF_FLAG_READ;
3078 if (fp->f_flag & FWRITE)
3079 kif->kf_flags |= KF_FLAG_WRITE;
3080 if (fp->f_flag & FAPPEND)
3081 kif->kf_flags |= KF_FLAG_APPEND;
3082 if (fp->f_flag & FASYNC)
3083 kif->kf_flags |= KF_FLAG_ASYNC;
3084 if (fp->f_flag & FFSYNC)
3085 kif->kf_flags |= KF_FLAG_FSYNC;
3086 if (fp->f_flag & FNONBLOCK)
3087 kif->kf_flags |= KF_FLAG_NONBLOCK;
3088 if (fp->f_flag & O_DIRECT)
3089 kif->kf_flags |= KF_FLAG_DIRECT;
3090 if (fp->f_flag & FHASLOCK)
3091 kif->kf_flags |= KF_FLAG_HASLOCK;
3092 kif->kf_offset = fp->f_offset;
3095 switch (vp->v_type) {
3097 kif->kf_vnode_type = KF_VTYPE_VNON;
3100 kif->kf_vnode_type = KF_VTYPE_VREG;
3103 kif->kf_vnode_type = KF_VTYPE_VDIR;
3106 kif->kf_vnode_type = KF_VTYPE_VBLK;
3109 kif->kf_vnode_type = KF_VTYPE_VCHR;
3112 kif->kf_vnode_type = KF_VTYPE_VLNK;
3115 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3118 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3121 kif->kf_vnode_type = KF_VTYPE_VBAD;
3124 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3128 * It is OK to drop the filedesc lock here as we will
3129 * re-validate and re-evaluate its properties when
3130 * the loop continues.
3134 FILEDESC_SUNLOCK(fdp);
3135 vn_fullpath(curthread, vp, &fullpath, &freepath);
3136 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3138 VFS_UNLOCK_GIANT(vfslocked);
3139 strlcpy(kif->kf_path, fullpath,
3140 sizeof(kif->kf_path));
3141 if (freepath != NULL)
3142 free(freepath, M_TEMP);
3143 FILEDESC_SLOCK(fdp);
3146 struct sockaddr *sa;
3148 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3149 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3150 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3153 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3154 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3155 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3158 kif->kf_sock_domain =
3159 so->so_proto->pr_domain->dom_family;
3160 kif->kf_sock_type = so->so_type;
3161 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3164 strlcpy(kif->kf_path, tty_devname(tp),
3165 sizeof(kif->kf_path));
3168 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3169 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3173 FILEDESC_SUNLOCK(fdp);
3179 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3180 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3181 #endif /* COMPAT_FREEBSD7 */
3183 #ifdef KINFO_FILE_SIZE
3184 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3188 export_fd_for_sysctl(void *data, int type, int fd, int fflags, int refcnt,
3189 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3190 struct kinfo_file *kif, struct sysctl_req *req)
3195 } fflags_table[] = {
3196 { FAPPEND, KF_FLAG_APPEND },
3197 { FASYNC, KF_FLAG_ASYNC },
3198 { FFSYNC, KF_FLAG_FSYNC },
3199 { FHASLOCK, KF_FLAG_HASLOCK },
3200 { FNONBLOCK, KF_FLAG_NONBLOCK },
3201 { FREAD, KF_FLAG_READ },
3202 { FWRITE, KF_FLAG_WRITE },
3203 { O_CREAT, KF_FLAG_CREAT },
3204 { O_DIRECT, KF_FLAG_DIRECT },
3205 { O_EXCL, KF_FLAG_EXCL },
3206 { O_EXEC, KF_FLAG_EXEC },
3207 { O_EXLOCK, KF_FLAG_EXLOCK },
3208 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3209 { O_SHLOCK, KF_FLAG_SHLOCK },
3210 { O_TRUNC, KF_FLAG_TRUNC }
3212 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3214 int error, vfslocked;
3217 bzero(kif, sizeof(*kif));
3221 vp = (struct vnode *)data;
3222 error = fill_vnode_info(vp, kif);
3223 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3225 VFS_UNLOCK_GIANT(vfslocked);
3227 case KF_TYPE_SOCKET:
3228 error = fill_socket_info((struct socket *)data, kif);
3231 error = fill_pipe_info((struct pipe *)data, kif);
3234 error = fill_pts_info((struct tty *)data, kif);
3236 case KF_TYPE_PROCDESC:
3237 error = fill_procdesc_info((struct procdesc *)data, kif);
3240 error = fill_shm_info((struct file *)data, kif);
3246 kif->kf_status |= KF_ATTR_VALID;
3249 * Translate file access flags.
3251 for (i = 0; i < NFFLAGS; i++)
3252 if (fflags & fflags_table[i].fflag)
3253 kif->kf_flags |= fflags_table[i].kf_fflag;
3255 kif->kf_flags |= KF_FLAG_CAPABILITY;
3257 kif->kf_cap_rights = fd_cap_rights;
3259 kif->kf_type = type;
3260 kif->kf_ref_count = refcnt;
3261 kif->kf_offset = offset;
3262 /* Pack record size down */
3263 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3264 strlen(kif->kf_path) + 1;
3265 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3266 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3271 * Get per-process file descriptors for use by procstat(1), et al.
3274 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3277 struct filedesc *fdp;
3278 struct kinfo_file *kif;
3280 struct vnode *cttyvp, *textvp, *tracevp;
3284 int error, i, *name;
3285 int fd_is_cap, type, refcnt, fflags;
3286 cap_rights_t fd_cap_rights;
3289 if ((p = pfind((pid_t)name[0])) == NULL)
3291 if ((error = p_candebug(curthread, p))) {
3296 tracevp = p->p_tracevp;
3297 if (tracevp != NULL)
3300 textvp = p->p_textvp;
3303 /* Controlling tty. */
3305 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3306 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3312 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3313 if (tracevp != NULL)
3314 export_fd_for_sysctl(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3315 FREAD | FWRITE, -1, -1, 0, 0, kif, req);
3317 export_fd_for_sysctl(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3318 FREAD, -1, -1, 0, 0, kif, req);
3320 export_fd_for_sysctl(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3321 FREAD | FWRITE, -1, -1, 0, 0, kif, req);
3324 FILEDESC_SLOCK(fdp);
3325 /* working directory */
3326 if (fdp->fd_cdir != NULL) {
3328 data = fdp->fd_cdir;
3329 FILEDESC_SUNLOCK(fdp);
3330 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3331 FREAD, -1, -1, 0, 0, kif, req);
3332 FILEDESC_SLOCK(fdp);
3334 /* root directory */
3335 if (fdp->fd_rdir != NULL) {
3337 data = fdp->fd_rdir;
3338 FILEDESC_SUNLOCK(fdp);
3339 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3340 FREAD, -1, -1, 0, 0, kif, req);
3341 FILEDESC_SLOCK(fdp);
3343 /* jail directory */
3344 if (fdp->fd_jdir != NULL) {
3346 data = fdp->fd_jdir;
3347 FILEDESC_SUNLOCK(fdp);
3348 export_fd_for_sysctl(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3349 FREAD, -1, -1, 0, 0, kif, req);
3350 FILEDESC_SLOCK(fdp);
3352 for (i = 0; i < fdp->fd_nfiles; i++) {
3353 if ((fp = fdp->fd_ofiles[i]) == NULL)
3361 * When reporting a capability, most fields will be from the
3362 * underlying object, but do mark as a capability and export
3363 * the capability rights mask.
3365 if (fp->f_type == DTYPE_CAPABILITY) {
3367 fd_cap_rights = cap_rights(fp);
3368 (void)cap_funwrap(fp, 0, &fp);
3370 #else /* !CAPABILITIES */
3371 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3372 ("sysctl_kern_proc_filedesc: saw capability"));
3374 switch (fp->f_type) {
3376 type = KF_TYPE_VNODE;
3382 type = KF_TYPE_SOCKET;
3387 type = KF_TYPE_PIPE;
3392 type = KF_TYPE_FIFO;
3398 type = KF_TYPE_KQUEUE;
3402 type = KF_TYPE_CRYPTO;
3406 type = KF_TYPE_MQUEUE;
3424 case DTYPE_PROCDESC:
3425 type = KF_TYPE_PROCDESC;
3431 type = KF_TYPE_UNKNOWN;
3434 refcnt = fp->f_count;
3435 fflags = fp->f_flag;
3436 offset = fp->f_offset;
3439 * Create sysctl entry.
3440 * It is OK to drop the filedesc lock here as we will
3441 * re-validate and re-evaluate its properties when
3442 * the loop continues.
3444 oldidx = req->oldidx;
3445 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3446 FILEDESC_SUNLOCK(fdp);
3447 error = export_fd_for_sysctl(data, type, i, fflags, refcnt,
3448 offset, fd_is_cap, fd_cap_rights, kif, req);
3449 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3450 FILEDESC_SLOCK(fdp);
3452 if (error == ENOMEM) {
3454 * The hack to keep the ABI of sysctl
3455 * kern.proc.filedesc intact, but not
3456 * to account a partially copied
3457 * kinfo_file into the oldidx.
3459 req->oldidx = oldidx;
3465 FILEDESC_SUNLOCK(fdp);
3474 vntype_to_kinfo(int vtype)
3479 } vtypes_table[] = {
3480 { VBAD, KF_VTYPE_VBAD },
3481 { VBLK, KF_VTYPE_VBLK },
3482 { VCHR, KF_VTYPE_VCHR },
3483 { VDIR, KF_VTYPE_VDIR },
3484 { VFIFO, KF_VTYPE_VFIFO },
3485 { VLNK, KF_VTYPE_VLNK },
3486 { VNON, KF_VTYPE_VNON },
3487 { VREG, KF_VTYPE_VREG },
3488 { VSOCK, KF_VTYPE_VSOCK }
3490 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3494 * Perform vtype translation.
3496 for (i = 0; i < NVTYPES; i++)
3497 if (vtypes_table[i].vtype == vtype)
3500 return (vtypes_table[i].kf_vtype);
3502 return (KF_VTYPE_UNKNOWN);
3506 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3509 char *fullpath, *freepath;
3510 int error, vfslocked;
3514 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3517 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3519 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3521 if (freepath != NULL)
3522 free(freepath, M_TEMP);
3525 * Retrieve vnode attributes.
3527 va.va_fsid = VNOVAL;
3529 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3530 vn_lock(vp, LK_SHARED | LK_RETRY);
3531 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3533 VFS_UNLOCK_GIANT(vfslocked);
3536 if (va.va_fsid != VNOVAL)
3537 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3539 kif->kf_un.kf_file.kf_file_fsid =
3540 vp->v_mount->mnt_stat.f_fsid.val[0];
3541 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3542 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3543 kif->kf_un.kf_file.kf_file_size = va.va_size;
3544 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3549 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3551 struct sockaddr *sa;
3552 struct inpcb *inpcb;
3553 struct unpcb *unpcb;
3558 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3559 kif->kf_sock_type = so->so_type;
3560 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3561 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3562 switch(kif->kf_sock_domain) {
3565 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3566 if (so->so_pcb != NULL) {
3567 inpcb = (struct inpcb *)(so->so_pcb);
3568 kif->kf_un.kf_sock.kf_sock_inpcb =
3569 (uintptr_t)inpcb->inp_ppcb;
3574 if (so->so_pcb != NULL) {
3575 unpcb = (struct unpcb *)(so->so_pcb);
3576 if (unpcb->unp_conn) {
3577 kif->kf_un.kf_sock.kf_sock_unpconn =
3578 (uintptr_t)unpcb->unp_conn;
3579 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3580 so->so_rcv.sb_state;
3581 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3582 so->so_snd.sb_state;
3587 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3588 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3589 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3592 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3593 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3594 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3597 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3598 sizeof(kif->kf_path));
3603 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3608 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3609 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3614 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3619 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3620 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3621 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3626 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3631 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3636 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3642 if (fp->f_data == NULL)
3644 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3646 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3647 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3648 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3652 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3653 sysctl_kern_proc_filedesc, "Process filedesc entries");
3657 * For the purposes of debugging, generate a human-readable string for the
3661 file_type_to_name(short type)
3691 * For the purposes of debugging, identify a process (if any, perhaps one of
3692 * many) that references the passed file in its file descriptor array. Return
3695 static struct proc *
3696 file_to_first_proc(struct file *fp)
3698 struct filedesc *fdp;
3702 FOREACH_PROC_IN_SYSTEM(p) {
3703 if (p->p_state == PRS_NEW)
3708 for (n = 0; n < fdp->fd_nfiles; n++) {
3709 if (fp == fdp->fd_ofiles[n])
3717 db_print_file(struct file *fp, int header)
3722 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3723 "File", "Type", "Data", "Flag", "GCFl", "Count",
3724 "MCount", "Vnode", "FPID", "FCmd");
3725 p = file_to_first_proc(fp);
3726 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3727 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3728 0, fp->f_count, 0, fp->f_vnode,
3729 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3732 DB_SHOW_COMMAND(file, db_show_file)
3737 db_printf("usage: show file <addr>\n");
3740 fp = (struct file *)addr;
3741 db_print_file(fp, 1);
3744 DB_SHOW_COMMAND(files, db_show_files)
3746 struct filedesc *fdp;
3753 FOREACH_PROC_IN_SYSTEM(p) {
3754 if (p->p_state == PRS_NEW)
3756 if ((fdp = p->p_fd) == NULL)
3758 for (n = 0; n < fdp->fd_nfiles; ++n) {
3759 if ((fp = fdp->fd_ofiles[n]) == NULL)
3761 db_print_file(fp, header);
3768 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3769 &maxfilesperproc, 0, "Maximum files allowed open per process");
3771 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3772 &maxfiles, 0, "Maximum number of files");
3774 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3775 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3779 filelistinit(void *dummy)
3782 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3783 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3784 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3785 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3787 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3789 /*-------------------------------------------------------------------*/
3792 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3799 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3806 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3813 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3820 badfo_kqfilter(struct file *fp, struct knote *kn)
3827 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3834 badfo_close(struct file *fp, struct thread *td)
3841 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3849 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3856 struct fileops badfileops = {
3857 .fo_read = badfo_readwrite,
3858 .fo_write = badfo_readwrite,
3859 .fo_truncate = badfo_truncate,
3860 .fo_ioctl = badfo_ioctl,
3861 .fo_poll = badfo_poll,
3862 .fo_kqfilter = badfo_kqfilter,
3863 .fo_stat = badfo_stat,
3864 .fo_close = badfo_close,
3865 .fo_chmod = badfo_chmod,
3866 .fo_chown = badfo_chown,
3870 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3878 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3885 /*-------------------------------------------------------------------*/
3888 * File Descriptor pseudo-device driver (/dev/fd/).
3890 * Opening minor device N dup()s the file (if any) connected to file
3891 * descriptor N belonging to the calling process. Note that this driver
3892 * consists of only the ``open()'' routine, because all subsequent
3893 * references to this file will be direct to the other driver.
3895 * XXX: we could give this one a cloning event handler if necessary.
3900 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3904 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3905 * the file descriptor being sought for duplication. The error
3906 * return ensures that the vnode for this device will be released
3907 * by vn_open. Open will detect this special error and take the
3908 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3909 * will simply report the error.
3911 td->td_dupfd = dev2unit(dev);
3915 static struct cdevsw fildesc_cdevsw = {
3916 .d_version = D_VERSION,
3922 fildesc_drvinit(void *unused)
3926 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3927 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3928 make_dev_alias(dev, "stdin");
3929 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3930 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3931 make_dev_alias(dev, "stdout");
3932 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3933 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3934 make_dev_alias(dev, "stderr");
3937 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);