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>
59 #include <sys/limits.h>
61 #include <sys/malloc.h>
63 #include <sys/mount.h>
64 #include <sys/mqueue.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/selinfo.h>
71 #include <sys/procdesc.h>
72 #include <sys/protosw.h>
73 #include <sys/racct.h>
74 #include <sys/resourcevar.h>
76 #include <sys/signalvar.h>
77 #include <sys/socketvar.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysctl.h>
82 #include <sys/sysproto.h>
84 #include <sys/unistd.h>
86 #include <sys/unpcb.h>
88 #include <sys/vnode.h>
90 #include <sys/ktrace.h>
95 #include <netinet/in.h>
96 #include <netinet/in_pcb.h>
98 #include <security/audit/audit.h>
105 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
106 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
107 "file desc to leader structures");
108 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
110 MALLOC_DECLARE(M_FADVISE);
112 static uma_zone_t file_zone;
114 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
116 /* Flags for do_dup() */
117 #define DUP_FIXED 0x1 /* Force fixed allocation */
118 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
119 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
121 static int do_dup(struct thread *td, int flags, int old, int new,
123 static int fd_first_free(struct filedesc *, int, int);
124 static int fd_last_used(struct filedesc *, int, int);
125 static void fdgrowtable(struct filedesc *, int);
126 static void fdunused(struct filedesc *fdp, int fd);
127 static void fdused(struct filedesc *fdp, int fd);
128 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
129 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
130 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
131 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
132 static int fill_procdesc_info(struct procdesc *pdp,
133 struct kinfo_file *kif);
134 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
135 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
138 * A process is initially started out with NDFILE descriptors stored within
139 * this structure, selected to be enough for typical applications based on
140 * the historical limit of 20 open files (and the usage of descriptors by
141 * shells). If these descriptors are exhausted, a larger descriptor table
142 * may be allocated, up to a process' resource limit; the internal arrays
146 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
147 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
148 #define NDSLOT(x) ((x) / NDENTRIES)
149 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
150 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
153 * Storage required per open file descriptor.
155 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
158 * Storage to hold unused ofiles that need to be reclaimed.
161 struct file **ft_table;
162 SLIST_ENTRY(freetable) ft_next;
166 * Basic allocation of descriptors:
167 * one of the above, plus arrays for NDFILE descriptors.
170 struct filedesc fd_fd;
172 * ofiles which need to be reclaimed on free.
174 SLIST_HEAD(,freetable) fd_free;
176 * These arrays are used when the number of open files is
177 * <= NDFILE, and are then pointed to by the pointers above.
179 struct file *fd_dfiles[NDFILE];
180 char fd_dfileflags[NDFILE];
181 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
185 * Descriptor management.
187 volatile int openfiles; /* actual number of open files */
188 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
189 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
191 /* A mutex to protect the association between a proc and filedesc. */
192 static struct mtx fdesc_mtx;
195 * Find the first zero bit in the given bitmap, starting at low and not
196 * exceeding size - 1.
199 fd_first_free(struct filedesc *fdp, int low, int size)
201 NDSLOTTYPE *map = fdp->fd_map;
209 if (low % NDENTRIES) {
210 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
211 if ((mask &= ~map[off]) != 0UL)
212 return (off * NDENTRIES + ffsl(mask) - 1);
215 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
216 if (map[off] != ~0UL)
217 return (off * NDENTRIES + ffsl(~map[off]) - 1);
222 * Find the highest non-zero bit in the given bitmap, starting at low and
223 * not exceeding size - 1.
226 fd_last_used(struct filedesc *fdp, int low, int size)
228 NDSLOTTYPE *map = fdp->fd_map;
236 if (size % NDENTRIES) {
237 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
238 if ((mask &= map[off]) != 0)
239 return (off * NDENTRIES + flsl(mask) - 1);
242 for (minoff = NDSLOT(low); off >= minoff; --off)
244 return (off * NDENTRIES + flsl(map[off]) - 1);
249 fdisused(struct filedesc *fdp, int fd)
251 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
252 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
253 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
257 * Mark a file descriptor as used.
260 fdused(struct filedesc *fdp, int fd)
263 FILEDESC_XLOCK_ASSERT(fdp);
264 KASSERT(!fdisused(fdp, fd),
265 ("fd already used"));
267 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
268 if (fd > fdp->fd_lastfile)
269 fdp->fd_lastfile = fd;
270 if (fd == fdp->fd_freefile)
271 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
275 * Mark a file descriptor as unused.
278 fdunused(struct filedesc *fdp, int fd)
281 FILEDESC_XLOCK_ASSERT(fdp);
282 KASSERT(fdisused(fdp, fd),
283 ("fd is already unused"));
284 KASSERT(fdp->fd_ofiles[fd] == NULL,
285 ("fd is still in use"));
287 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288 if (fd < fdp->fd_freefile)
289 fdp->fd_freefile = fd;
290 if (fd == fdp->fd_lastfile)
291 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
295 * System calls on descriptors.
297 #ifndef _SYS_SYSPROTO_H_
298 struct getdtablesize_args {
304 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
306 struct proc *p = td->td_proc;
311 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
312 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
314 if (lim < td->td_retval[0])
315 td->td_retval[0] = lim;
320 * Duplicate a file descriptor to a particular value.
322 * Note: keep in mind that a potential race condition exists when closing
323 * descriptors from a shared descriptor table (via rfork).
325 #ifndef _SYS_SYSPROTO_H_
333 sys_dup2(struct thread *td, struct dup2_args *uap)
336 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
341 * Duplicate a file descriptor.
343 #ifndef _SYS_SYSPROTO_H_
350 sys_dup(struct thread *td, struct dup_args *uap)
353 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
357 * The file control system call.
359 #ifndef _SYS_SYSPROTO_H_
368 sys_fcntl(struct thread *td, struct fcntl_args *uap)
383 * Convert old flock structure to new.
385 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
386 fl.l_start = ofl.l_start;
387 fl.l_len = ofl.l_len;
388 fl.l_pid = ofl.l_pid;
389 fl.l_type = ofl.l_type;
390 fl.l_whence = ofl.l_whence;
410 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
419 error = kern_fcntl(td, uap->fd, cmd, arg);
422 if (uap->cmd == F_OGETLK) {
423 ofl.l_start = fl.l_start;
424 ofl.l_len = fl.l_len;
425 ofl.l_pid = fl.l_pid;
426 ofl.l_type = fl.l_type;
427 ofl.l_whence = fl.l_whence;
428 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
429 } else if (uap->cmd == F_GETLK) {
430 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
435 static inline struct file *
436 fdtofp(int fd, struct filedesc *fdp)
440 FILEDESC_LOCK_ASSERT(fdp);
441 if ((unsigned)fd >= fdp->fd_nfiles ||
442 (fp = fdp->fd_ofiles[fd]) == NULL)
448 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
451 *fpp = fdtofp(fd, fdp);
456 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
457 int err = cap_funwrap(*fpp, rights, fpp);
463 #endif /* CAPABILITIES */
468 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
470 struct filedesc *fdp;
491 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
494 case F_DUPFD_CLOEXEC:
496 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
502 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
505 case F_DUP2FD_CLOEXEC:
507 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
513 if ((fp = fdtofp(fd, fdp)) == NULL) {
514 FILEDESC_SUNLOCK(fdp);
518 pop = &fdp->fd_ofileflags[fd];
519 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
520 FILEDESC_SUNLOCK(fdp);
525 if ((fp = fdtofp(fd, fdp)) == NULL) {
526 FILEDESC_XUNLOCK(fdp);
530 pop = &fdp->fd_ofileflags[fd];
531 *pop = (*pop &~ UF_EXCLOSE) |
532 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
533 FILEDESC_XUNLOCK(fdp);
538 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
540 FILEDESC_SUNLOCK(fdp);
543 td->td_retval[0] = OFLAGS(fp->f_flag);
544 FILEDESC_SUNLOCK(fdp);
549 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
551 FILEDESC_SUNLOCK(fdp);
555 FILEDESC_SUNLOCK(fdp);
557 tmp = flg = fp->f_flag;
559 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
560 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
561 tmp = fp->f_flag & FNONBLOCK;
562 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
567 tmp = fp->f_flag & FASYNC;
568 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
573 atomic_clear_int(&fp->f_flag, FNONBLOCK);
575 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
581 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
583 FILEDESC_SUNLOCK(fdp);
587 FILEDESC_SUNLOCK(fdp);
588 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
590 td->td_retval[0] = tmp;
596 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
598 FILEDESC_SUNLOCK(fdp);
602 FILEDESC_SUNLOCK(fdp);
604 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
609 error = priv_check(td, PRIV_NFS_LOCKD);
617 /* FALLTHROUGH F_SETLK */
622 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
624 FILEDESC_SUNLOCK(fdp);
627 if (fp->f_type != DTYPE_VNODE) {
628 FILEDESC_SUNLOCK(fdp);
632 flp = (struct flock *)arg;
633 if (flp->l_whence == SEEK_CUR) {
634 foffset = foffset_get(fp);
637 foffset > OFF_MAX - flp->l_start)) {
638 FILEDESC_SUNLOCK(fdp);
642 flp->l_start += foffset;
646 * VOP_ADVLOCK() may block.
649 FILEDESC_SUNLOCK(fdp);
651 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
652 switch (flp->l_type) {
654 if ((fp->f_flag & FREAD) == 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 if ((fp->f_flag & FWRITE) == 0) {
669 PROC_LOCK(p->p_leader);
670 p->p_leader->p_flag |= P_ADVLOCK;
671 PROC_UNLOCK(p->p_leader);
672 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
676 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
681 * Temporary api for testing remote lock
684 if (flg != F_REMOTE) {
688 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
689 F_UNLCKSYS, flp, flg);
695 VFS_UNLOCK_GIANT(vfslocked);
697 /* Check for race with close */
699 if ((unsigned) fd >= fdp->fd_nfiles ||
700 fp != fdp->fd_ofiles[fd]) {
701 FILEDESC_SUNLOCK(fdp);
702 flp->l_whence = SEEK_SET;
705 flp->l_type = F_UNLCK;
706 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
707 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708 F_UNLCK, flp, F_POSIX);
709 VFS_UNLOCK_GIANT(vfslocked);
712 FILEDESC_SUNLOCK(fdp);
718 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
720 FILEDESC_SUNLOCK(fdp);
723 if (fp->f_type != DTYPE_VNODE) {
724 FILEDESC_SUNLOCK(fdp);
728 flp = (struct flock *)arg;
729 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
730 flp->l_type != F_UNLCK) {
731 FILEDESC_SUNLOCK(fdp);
735 if (flp->l_whence == SEEK_CUR) {
736 foffset = foffset_get(fp);
737 if ((flp->l_start > 0 &&
738 foffset > OFF_MAX - flp->l_start) ||
740 foffset < OFF_MIN - flp->l_start)) {
741 FILEDESC_SUNLOCK(fdp);
745 flp->l_start += foffset;
748 * VOP_ADVLOCK() may block.
751 FILEDESC_SUNLOCK(fdp);
753 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
754 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
756 VFS_UNLOCK_GIANT(vfslocked);
762 arg = arg ? 128 * 1024: 0;
766 if ((fp = fdtofp(fd, fdp)) == NULL) {
767 FILEDESC_SUNLOCK(fdp);
771 if (fp->f_type != DTYPE_VNODE) {
772 FILEDESC_SUNLOCK(fdp);
777 FILEDESC_SUNLOCK(fdp);
780 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
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:
792 VFS_UNLOCK_GIANT(vfslocked);
796 new = old = fp->f_flag;
798 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
807 VFS_UNLOCK_GIANT(vfslocked);
812 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
815 do_dup(struct thread *td, int flags, int old, int new,
818 struct filedesc *fdp;
822 int error, holdleaders, maxfd;
828 * Verify we have a valid descriptor to dup from and possibly to
829 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
830 * return EINVAL when the new descriptor is out of bounds.
835 return (flags & DUP_FCNTL ? EINVAL : EBADF);
837 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
840 return (flags & DUP_FCNTL ? EINVAL : EBADF);
843 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
844 FILEDESC_XUNLOCK(fdp);
847 if (flags & DUP_FIXED && old == new) {
849 if (flags & DUP_CLOEXEC)
850 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
851 FILEDESC_XUNLOCK(fdp);
854 fp = fdp->fd_ofiles[old];
858 * If the caller specified a file descriptor, make sure the file
859 * table is large enough to hold it, and grab it. Otherwise, just
860 * allocate a new descriptor the usual way. Since the filedesc
861 * lock may be temporarily dropped in the process, we have to look
864 if (flags & DUP_FIXED) {
865 if (new >= fdp->fd_nfiles) {
867 * The resource limits are here instead of e.g.
868 * fdalloc(), because the file descriptor table may be
869 * shared between processes, so we can't really use
870 * racct_add()/racct_sub(). Instead of counting the
871 * number of actually allocated descriptors, just put
872 * the limit on the size of the file descriptor table.
876 error = racct_set(p, RACCT_NOFILE, new + 1);
879 FILEDESC_XUNLOCK(fdp);
884 fdgrowtable(fdp, new + 1);
886 if (fdp->fd_ofiles[new] == NULL)
889 if ((error = fdalloc(td, new, &new)) != 0) {
890 FILEDESC_XUNLOCK(fdp);
897 * If the old file changed out from under us then treat it as a
898 * bad file descriptor. Userland should do its own locking to
901 if (fdp->fd_ofiles[old] != fp) {
902 /* we've allocated a descriptor which we won't use */
903 if (fdp->fd_ofiles[new] == NULL)
905 FILEDESC_XUNLOCK(fdp);
910 ("new fd is same as old"));
913 * Save info on the descriptor being overwritten. We cannot close
914 * it without introducing an ownership race for the slot, since we
915 * need to drop the filedesc lock to call closef().
917 * XXX this duplicates parts of close().
919 delfp = fdp->fd_ofiles[new];
922 if (td->td_proc->p_fdtol != NULL) {
924 * Ask fdfree() to sleep to ensure that all relevant
925 * process leaders can be traversed in closef().
927 fdp->fd_holdleaderscount++;
933 * Duplicate the source descriptor
935 fdp->fd_ofiles[new] = fp;
936 if ((flags & DUP_CLOEXEC) != 0)
937 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
939 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
940 if (new > fdp->fd_lastfile)
941 fdp->fd_lastfile = new;
945 * If we dup'd over a valid file, we now own the reference to it
946 * and must dispose of it using closef() semantics (as if a
947 * close() were performed on it).
949 * XXX this duplicates parts of close().
952 knote_fdclose(td, new);
953 if (delfp->f_type == DTYPE_MQUEUE)
954 mq_fdclose(td, new, delfp);
955 FILEDESC_XUNLOCK(fdp);
956 (void) closef(delfp, td);
959 fdp->fd_holdleaderscount--;
960 if (fdp->fd_holdleaderscount == 0 &&
961 fdp->fd_holdleaderswakeup != 0) {
962 fdp->fd_holdleaderswakeup = 0;
963 wakeup(&fdp->fd_holdleaderscount);
965 FILEDESC_XUNLOCK(fdp);
968 FILEDESC_XUNLOCK(fdp);
974 * If sigio is on the list associated with a process or process group,
975 * disable signalling from the device, remove sigio from the list and
979 funsetown(struct sigio **sigiop)
989 *(sigio->sio_myref) = NULL;
990 if ((sigio)->sio_pgid < 0) {
991 struct pgrp *pg = (sigio)->sio_pgrp;
993 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
997 struct proc *p = (sigio)->sio_proc;
999 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1000 sigio, sio_pgsigio);
1004 crfree(sigio->sio_ucred);
1005 free(sigio, M_SIGIO);
1009 * Free a list of sigio structures.
1010 * We only need to lock the SIGIO_LOCK because we have made ourselves
1011 * inaccessible to callers of fsetown and therefore do not need to lock
1012 * the proc or pgrp struct for the list manipulation.
1015 funsetownlst(struct sigiolst *sigiolst)
1019 struct sigio *sigio;
1021 sigio = SLIST_FIRST(sigiolst);
1028 * Every entry of the list should belong
1029 * to a single proc or pgrp.
1031 if (sigio->sio_pgid < 0) {
1032 pg = sigio->sio_pgrp;
1033 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1034 } else /* if (sigio->sio_pgid > 0) */ {
1035 p = sigio->sio_proc;
1036 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1040 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1041 *(sigio->sio_myref) = NULL;
1043 KASSERT(sigio->sio_pgid < 0,
1044 ("Proc sigio in pgrp sigio list"));
1045 KASSERT(sigio->sio_pgrp == pg,
1046 ("Bogus pgrp in sigio list"));
1048 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1051 } else /* if (p != NULL) */ {
1052 KASSERT(sigio->sio_pgid > 0,
1053 ("Pgrp sigio in proc sigio list"));
1054 KASSERT(sigio->sio_proc == p,
1055 ("Bogus proc in sigio list"));
1057 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1062 crfree(sigio->sio_ucred);
1063 free(sigio, M_SIGIO);
1070 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1072 * After permission checking, add a sigio structure to the sigio list for
1073 * the process or process group.
1076 fsetown(pid_t pgid, struct sigio **sigiop)
1080 struct sigio *sigio;
1090 /* Allocate and fill in the new sigio out of locks. */
1091 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1092 sigio->sio_pgid = pgid;
1093 sigio->sio_ucred = crhold(curthread->td_ucred);
1094 sigio->sio_myref = sigiop;
1096 sx_slock(&proctree_lock);
1105 * Policy - Don't allow a process to FSETOWN a process
1106 * in another session.
1108 * Remove this test to allow maximum flexibility or
1109 * restrict FSETOWN to the current process or process
1110 * group for maximum safety.
1113 if (proc->p_session != curthread->td_proc->p_session) {
1119 } else /* if (pgid < 0) */ {
1120 pgrp = pgfind(-pgid);
1128 * Policy - Don't allow a process to FSETOWN a process
1129 * in another session.
1131 * Remove this test to allow maximum flexibility or
1132 * restrict FSETOWN to the current process or process
1133 * group for maximum safety.
1135 if (pgrp->pg_session != curthread->td_proc->p_session) {
1146 * Since funsetownlst() is called without the proctree
1147 * locked, we need to check for P_WEXIT.
1148 * XXX: is ESRCH correct?
1150 if ((proc->p_flag & P_WEXIT) != 0) {
1155 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1156 sigio->sio_proc = proc;
1160 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1161 sigio->sio_pgrp = pgrp;
1164 sx_sunlock(&proctree_lock);
1171 sx_sunlock(&proctree_lock);
1172 crfree(sigio->sio_ucred);
1173 free(sigio, M_SIGIO);
1178 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1182 struct sigio **sigiop;
1187 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1193 * Close a file descriptor.
1195 #ifndef _SYS_SYSPROTO_H_
1204 struct close_args *uap;
1207 return (kern_close(td, uap->fd));
1215 struct filedesc *fdp;
1216 struct file *fp, *fp_object;
1222 fdp = td->td_proc->p_fd;
1224 AUDIT_SYSCLOSE(td, fd);
1226 FILEDESC_XLOCK(fdp);
1227 if ((unsigned)fd >= fdp->fd_nfiles ||
1228 (fp = fdp->fd_ofiles[fd]) == NULL) {
1229 FILEDESC_XUNLOCK(fdp);
1232 fdp->fd_ofiles[fd] = NULL;
1233 fdp->fd_ofileflags[fd] = 0;
1235 if (td->td_proc->p_fdtol != NULL) {
1237 * Ask fdfree() to sleep to ensure that all relevant
1238 * process leaders can be traversed in closef().
1240 fdp->fd_holdleaderscount++;
1245 * We now hold the fp reference that used to be owned by the
1246 * descriptor array. We have to unlock the FILEDESC *AFTER*
1247 * knote_fdclose to prevent a race of the fd getting opened, a knote
1248 * added, and deleteing a knote for the new fd.
1250 knote_fdclose(td, fd);
1253 * When we're closing an fd with a capability, we need to notify
1254 * mqueue if the underlying object is of type mqueue.
1256 (void)cap_funwrap(fp, 0, &fp_object);
1257 if (fp_object->f_type == DTYPE_MQUEUE)
1258 mq_fdclose(td, fd, fp_object);
1259 FILEDESC_XUNLOCK(fdp);
1261 error = closef(fp, td);
1263 FILEDESC_XLOCK(fdp);
1264 fdp->fd_holdleaderscount--;
1265 if (fdp->fd_holdleaderscount == 0 &&
1266 fdp->fd_holdleaderswakeup != 0) {
1267 fdp->fd_holdleaderswakeup = 0;
1268 wakeup(&fdp->fd_holdleaderscount);
1270 FILEDESC_XUNLOCK(fdp);
1276 * Close open file descriptors.
1278 #ifndef _SYS_SYSPROTO_H_
1279 struct closefrom_args {
1285 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1287 struct filedesc *fdp;
1290 fdp = td->td_proc->p_fd;
1291 AUDIT_ARG_FD(uap->lowfd);
1294 * Treat negative starting file descriptor values identical to
1295 * closefrom(0) which closes all files.
1299 FILEDESC_SLOCK(fdp);
1300 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1301 if (fdp->fd_ofiles[fd] != NULL) {
1302 FILEDESC_SUNLOCK(fdp);
1303 (void)kern_close(td, fd);
1304 FILEDESC_SLOCK(fdp);
1307 FILEDESC_SUNLOCK(fdp);
1311 #if defined(COMPAT_43)
1313 * Return status information about a file descriptor.
1315 #ifndef _SYS_SYSPROTO_H_
1316 struct ofstat_args {
1323 ofstat(struct thread *td, struct ofstat_args *uap)
1329 error = kern_fstat(td, uap->fd, &ub);
1332 error = copyout(&oub, uap->sb, sizeof(oub));
1336 #endif /* COMPAT_43 */
1339 * Return status information about a file descriptor.
1341 #ifndef _SYS_SYSPROTO_H_
1349 sys_fstat(struct thread *td, struct fstat_args *uap)
1354 error = kern_fstat(td, uap->fd, &ub);
1356 error = copyout(&ub, uap->sb, sizeof(ub));
1361 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1368 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1371 AUDIT_ARG_FILE(td->td_proc, fp);
1373 error = fo_stat(fp, sbp, td->td_ucred, td);
1376 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1383 * Return status information about a file descriptor.
1385 #ifndef _SYS_SYSPROTO_H_
1386 struct nfstat_args {
1393 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1399 error = kern_fstat(td, uap->fd, &ub);
1401 cvtnstat(&ub, &nub);
1402 error = copyout(&nub, uap->sb, sizeof(nub));
1408 * Return pathconf information about a file descriptor.
1410 #ifndef _SYS_SYSPROTO_H_
1411 struct fpathconf_args {
1418 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1424 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1427 /* If asynchronous I/O is available, it works for all descriptors. */
1428 if (uap->name == _PC_ASYNC_IO) {
1429 td->td_retval[0] = async_io_version;
1435 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1436 vn_lock(vp, LK_SHARED | LK_RETRY);
1437 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1439 VFS_UNLOCK_GIANT(vfslocked);
1440 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1441 if (uap->name != _PC_PIPE_BUF) {
1444 td->td_retval[0] = PIPE_BUF;
1456 * Grow the file table to accomodate (at least) nfd descriptors. This may
1457 * block and drop the filedesc lock, but it will reacquire it before
1461 fdgrowtable(struct filedesc *fdp, int nfd)
1463 struct filedesc0 *fdp0;
1464 struct freetable *fo;
1465 struct file **ntable;
1466 struct file **otable;
1468 int nnfiles, onfiles;
1471 FILEDESC_XLOCK_ASSERT(fdp);
1473 KASSERT(fdp->fd_nfiles > 0,
1474 ("zero-length file table"));
1476 /* compute the size of the new table */
1477 onfiles = fdp->fd_nfiles;
1478 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1479 if (nnfiles <= onfiles)
1480 /* the table is already large enough */
1483 /* allocate a new table and (if required) new bitmaps */
1484 FILEDESC_XUNLOCK(fdp);
1485 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1486 M_FILEDESC, M_ZERO | M_WAITOK);
1487 nfileflags = (char *)&ntable[nnfiles];
1488 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1489 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1490 M_FILEDESC, M_ZERO | M_WAITOK);
1493 FILEDESC_XLOCK(fdp);
1496 * We now have new tables ready to go. Since we dropped the
1497 * filedesc lock to call malloc(), watch out for a race.
1499 onfiles = fdp->fd_nfiles;
1500 if (onfiles >= nnfiles) {
1501 /* we lost the race, but that's OK */
1502 free(ntable, M_FILEDESC);
1504 free(nmap, M_FILEDESC);
1507 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1508 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1509 otable = fdp->fd_ofiles;
1510 fdp->fd_ofileflags = nfileflags;
1511 fdp->fd_ofiles = ntable;
1513 * We must preserve ofiles until the process exits because we can't
1514 * be certain that no threads have references to the old table via
1517 if (onfiles > NDFILE) {
1518 fo = (struct freetable *)&otable[onfiles];
1519 fdp0 = (struct filedesc0 *)fdp;
1520 fo->ft_table = otable;
1521 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1523 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1524 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1525 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1526 free(fdp->fd_map, M_FILEDESC);
1529 fdp->fd_nfiles = nnfiles;
1533 * Allocate a file descriptor for the process.
1536 fdalloc(struct thread *td, int minfd, int *result)
1538 struct proc *p = td->td_proc;
1539 struct filedesc *fdp = p->p_fd;
1545 FILEDESC_XLOCK_ASSERT(fdp);
1547 if (fdp->fd_freefile > minfd)
1548 minfd = fdp->fd_freefile;
1551 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1555 * Search the bitmap for a free descriptor. If none is found, try
1556 * to grow the file table. Keep at it until we either get a file
1557 * descriptor or run into process or system limits; fdgrowtable()
1558 * may drop the filedesc lock, so we're in a race.
1561 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1564 if (fd < fdp->fd_nfiles)
1568 error = racct_set(p, RACCT_NOFILE, min(fdp->fd_nfiles * 2, maxfd));
1573 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1577 * Perform some sanity checks, then mark the file descriptor as
1578 * used and return it to the caller.
1580 KASSERT(!fdisused(fdp, fd),
1581 ("fd_first_free() returned non-free descriptor"));
1582 KASSERT(fdp->fd_ofiles[fd] == NULL,
1583 ("free descriptor isn't"));
1584 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1591 * Check to see whether n user file descriptors are available to the process
1595 fdavail(struct thread *td, int n)
1597 struct proc *p = td->td_proc;
1598 struct filedesc *fdp = td->td_proc->p_fd;
1602 FILEDESC_LOCK_ASSERT(fdp);
1605 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1606 * call racct_add() from there instead of dealing with containers
1610 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1612 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1614 last = min(fdp->fd_nfiles, lim);
1615 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1616 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1617 if (*fpp == NULL && --n <= 0)
1624 * Create a new open file structure and allocate a file decriptor for the
1625 * process that refers to it. We add one reference to the file for the
1626 * descriptor table and one reference for resultfp. This is to prevent us
1627 * being preempted and the entry in the descriptor table closed after we
1628 * release the FILEDESC lock.
1631 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1636 error = falloc_noinstall(td, &fp);
1638 return (error); /* no reference held on error */
1640 error = finstall(td, fp, &fd, flags);
1642 fdrop(fp, td); /* one reference (fp only) */
1646 if (resultfp != NULL)
1647 *resultfp = fp; /* copy out result */
1649 fdrop(fp, td); /* release local reference */
1651 if (resultfd != NULL)
1658 * Create a new open file structure without allocating a file descriptor.
1661 falloc_noinstall(struct thread *td, struct file **resultfp)
1664 int maxuserfiles = maxfiles - (maxfiles / 20);
1665 static struct timeval lastfail;
1668 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1670 if ((openfiles >= maxuserfiles &&
1671 priv_check(td, PRIV_MAXFILES) != 0) ||
1672 openfiles >= maxfiles) {
1673 if (ppsratecheck(&lastfail, &curfail, 1)) {
1674 printf("kern.maxfiles limit exceeded by uid %i, "
1675 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1679 atomic_add_int(&openfiles, 1);
1680 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1681 refcount_init(&fp->f_count, 1);
1682 fp->f_cred = crhold(td->td_ucred);
1683 fp->f_ops = &badfileops;
1691 * Install a file in a file descriptor table.
1694 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1696 struct filedesc *fdp = td->td_proc->p_fd;
1699 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1700 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1702 FILEDESC_XLOCK(fdp);
1703 if ((error = fdalloc(td, 0, fd))) {
1704 FILEDESC_XUNLOCK(fdp);
1708 fdp->fd_ofiles[*fd] = fp;
1709 if ((flags & O_CLOEXEC) != 0)
1710 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1711 FILEDESC_XUNLOCK(fdp);
1716 * Build a new filedesc structure from another.
1717 * Copy the current, root, and jail root vnode references.
1720 fdinit(struct filedesc *fdp)
1722 struct filedesc0 *newfdp;
1724 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1725 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1727 FILEDESC_XLOCK(fdp);
1728 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1729 if (newfdp->fd_fd.fd_cdir)
1730 VREF(newfdp->fd_fd.fd_cdir);
1731 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1732 if (newfdp->fd_fd.fd_rdir)
1733 VREF(newfdp->fd_fd.fd_rdir);
1734 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1735 if (newfdp->fd_fd.fd_jdir)
1736 VREF(newfdp->fd_fd.fd_jdir);
1737 FILEDESC_XUNLOCK(fdp);
1740 /* Create the file descriptor table. */
1741 newfdp->fd_fd.fd_refcnt = 1;
1742 newfdp->fd_fd.fd_holdcnt = 1;
1743 newfdp->fd_fd.fd_cmask = CMASK;
1744 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1745 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1746 newfdp->fd_fd.fd_nfiles = NDFILE;
1747 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1748 newfdp->fd_fd.fd_lastfile = -1;
1749 return (&newfdp->fd_fd);
1752 static struct filedesc *
1753 fdhold(struct proc *p)
1755 struct filedesc *fdp;
1757 mtx_lock(&fdesc_mtx);
1761 mtx_unlock(&fdesc_mtx);
1766 fddrop(struct filedesc *fdp)
1768 struct filedesc0 *fdp0;
1769 struct freetable *ft;
1772 mtx_lock(&fdesc_mtx);
1773 i = --fdp->fd_holdcnt;
1774 mtx_unlock(&fdesc_mtx);
1778 FILEDESC_LOCK_DESTROY(fdp);
1779 fdp0 = (struct filedesc0 *)fdp;
1780 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1781 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1782 free(ft->ft_table, M_FILEDESC);
1784 free(fdp, M_FILEDESC);
1788 * Share a filedesc structure.
1791 fdshare(struct filedesc *fdp)
1794 FILEDESC_XLOCK(fdp);
1796 FILEDESC_XUNLOCK(fdp);
1801 * Unshare a filedesc structure, if necessary by making a copy
1804 fdunshare(struct proc *p, struct thread *td)
1807 FILEDESC_XLOCK(p->p_fd);
1808 if (p->p_fd->fd_refcnt > 1) {
1809 struct filedesc *tmp;
1811 FILEDESC_XUNLOCK(p->p_fd);
1812 tmp = fdcopy(p->p_fd);
1816 FILEDESC_XUNLOCK(p->p_fd);
1820 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1821 * this is to ease callers, not catch errors.
1824 fdcopy(struct filedesc *fdp)
1826 struct filedesc *newfdp;
1829 /* Certain daemons might not have file descriptors. */
1833 newfdp = fdinit(fdp);
1834 FILEDESC_SLOCK(fdp);
1835 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1836 FILEDESC_SUNLOCK(fdp);
1837 FILEDESC_XLOCK(newfdp);
1838 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1839 FILEDESC_XUNLOCK(newfdp);
1840 FILEDESC_SLOCK(fdp);
1842 /* copy all passable descriptors (i.e. not kqueue) */
1843 newfdp->fd_freefile = -1;
1844 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1845 if (fdisused(fdp, i) &&
1846 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1847 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1848 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1849 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1850 fhold(newfdp->fd_ofiles[i]);
1851 newfdp->fd_lastfile = i;
1853 if (newfdp->fd_freefile == -1)
1854 newfdp->fd_freefile = i;
1857 newfdp->fd_cmask = fdp->fd_cmask;
1858 FILEDESC_SUNLOCK(fdp);
1859 FILEDESC_XLOCK(newfdp);
1860 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1861 if (newfdp->fd_ofiles[i] != NULL)
1863 if (newfdp->fd_freefile == -1)
1864 newfdp->fd_freefile = i;
1865 FILEDESC_XUNLOCK(newfdp);
1870 * Release a filedesc structure.
1873 fdfree(struct thread *td)
1875 struct filedesc *fdp;
1878 struct filedesc_to_leader *fdtol;
1880 struct vnode *cdir, *jdir, *rdir, *vp;
1883 /* Certain daemons might not have file descriptors. */
1884 fdp = td->td_proc->p_fd;
1889 PROC_LOCK(td->td_proc);
1890 racct_set(td->td_proc, RACCT_NOFILE, 0);
1891 PROC_UNLOCK(td->td_proc);
1894 /* Check for special need to clear POSIX style locks */
1895 fdtol = td->td_proc->p_fdtol;
1896 if (fdtol != NULL) {
1897 FILEDESC_XLOCK(fdp);
1898 KASSERT(fdtol->fdl_refcount > 0,
1899 ("filedesc_to_refcount botch: fdl_refcount=%d",
1900 fdtol->fdl_refcount));
1901 if (fdtol->fdl_refcount == 1 &&
1902 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1903 for (i = 0, fpp = fdp->fd_ofiles;
1904 i <= fdp->fd_lastfile;
1907 (*fpp)->f_type != DTYPE_VNODE)
1911 FILEDESC_XUNLOCK(fdp);
1912 lf.l_whence = SEEK_SET;
1915 lf.l_type = F_UNLCK;
1917 locked = VFS_LOCK_GIANT(vp->v_mount);
1918 (void) VOP_ADVLOCK(vp,
1919 (caddr_t)td->td_proc->
1924 VFS_UNLOCK_GIANT(locked);
1925 FILEDESC_XLOCK(fdp);
1927 fpp = fdp->fd_ofiles + i;
1931 if (fdtol->fdl_refcount == 1) {
1932 if (fdp->fd_holdleaderscount > 0 &&
1933 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1935 * close() or do_dup() has cleared a reference
1936 * in a shared file descriptor table.
1938 fdp->fd_holdleaderswakeup = 1;
1939 sx_sleep(&fdp->fd_holdleaderscount,
1940 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1943 if (fdtol->fdl_holdcount > 0) {
1945 * Ensure that fdtol->fdl_leader remains
1946 * valid in closef().
1948 fdtol->fdl_wakeup = 1;
1949 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1954 fdtol->fdl_refcount--;
1955 if (fdtol->fdl_refcount == 0 &&
1956 fdtol->fdl_holdcount == 0) {
1957 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1958 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1961 td->td_proc->p_fdtol = NULL;
1962 FILEDESC_XUNLOCK(fdp);
1964 free(fdtol, M_FILEDESC_TO_LEADER);
1966 FILEDESC_XLOCK(fdp);
1967 i = --fdp->fd_refcnt;
1968 FILEDESC_XUNLOCK(fdp);
1972 fpp = fdp->fd_ofiles;
1973 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1975 FILEDESC_XLOCK(fdp);
1978 FILEDESC_XUNLOCK(fdp);
1979 (void) closef(fp, td);
1982 FILEDESC_XLOCK(fdp);
1984 /* XXX This should happen earlier. */
1985 mtx_lock(&fdesc_mtx);
1986 td->td_proc->p_fd = NULL;
1987 mtx_unlock(&fdesc_mtx);
1989 if (fdp->fd_nfiles > NDFILE)
1990 free(fdp->fd_ofiles, M_FILEDESC);
1991 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1992 free(fdp->fd_map, M_FILEDESC);
1996 cdir = fdp->fd_cdir;
1997 fdp->fd_cdir = NULL;
1998 rdir = fdp->fd_rdir;
1999 fdp->fd_rdir = NULL;
2000 jdir = fdp->fd_jdir;
2001 fdp->fd_jdir = NULL;
2002 FILEDESC_XUNLOCK(fdp);
2005 locked = VFS_LOCK_GIANT(cdir->v_mount);
2007 VFS_UNLOCK_GIANT(locked);
2010 locked = VFS_LOCK_GIANT(rdir->v_mount);
2012 VFS_UNLOCK_GIANT(locked);
2015 locked = VFS_LOCK_GIANT(jdir->v_mount);
2017 VFS_UNLOCK_GIANT(locked);
2024 * For setugid programs, we don't want to people to use that setugidness
2025 * to generate error messages which write to a file which otherwise would
2026 * otherwise be off-limits to the process. We check for filesystems where
2027 * the vnode can change out from under us after execve (like [lin]procfs).
2029 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2030 * sufficient. We also don't check for setugidness since we know we are.
2033 is_unsafe(struct file *fp)
2035 if (fp->f_type == DTYPE_VNODE) {
2036 struct vnode *vp = fp->f_vnode;
2038 if ((vp->v_vflag & VV_PROCDEP) != 0)
2045 * Make this setguid thing safe, if at all possible.
2048 setugidsafety(struct thread *td)
2050 struct filedesc *fdp;
2053 /* Certain daemons might not have file descriptors. */
2054 fdp = td->td_proc->p_fd;
2059 * Note: fdp->fd_ofiles may be reallocated out from under us while
2060 * we are blocked in a close. Be careful!
2062 FILEDESC_XLOCK(fdp);
2063 for (i = 0; i <= fdp->fd_lastfile; i++) {
2066 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2069 knote_fdclose(td, i);
2071 * NULL-out descriptor prior to close to avoid
2072 * a race while close blocks.
2074 fp = fdp->fd_ofiles[i];
2075 fdp->fd_ofiles[i] = NULL;
2076 fdp->fd_ofileflags[i] = 0;
2078 FILEDESC_XUNLOCK(fdp);
2079 (void) closef(fp, td);
2080 FILEDESC_XLOCK(fdp);
2083 FILEDESC_XUNLOCK(fdp);
2087 * If a specific file object occupies a specific file descriptor, close the
2088 * file descriptor entry and drop a reference on the file object. This is a
2089 * convenience function to handle a subsequent error in a function that calls
2090 * falloc() that handles the race that another thread might have closed the
2091 * file descriptor out from under the thread creating the file object.
2094 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2097 FILEDESC_XLOCK(fdp);
2098 if (fdp->fd_ofiles[idx] == fp) {
2099 fdp->fd_ofiles[idx] = NULL;
2101 FILEDESC_XUNLOCK(fdp);
2104 FILEDESC_XUNLOCK(fdp);
2108 * Close any files on exec?
2111 fdcloseexec(struct thread *td)
2113 struct filedesc *fdp;
2116 /* Certain daemons might not have file descriptors. */
2117 fdp = td->td_proc->p_fd;
2121 FILEDESC_XLOCK(fdp);
2124 * We cannot cache fd_ofiles or fd_ofileflags since operations
2125 * may block and rip them out from under us.
2127 for (i = 0; i <= fdp->fd_lastfile; i++) {
2128 if (fdp->fd_ofiles[i] != NULL &&
2129 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2130 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2133 knote_fdclose(td, i);
2135 * NULL-out descriptor prior to close to avoid
2136 * a race while close blocks.
2138 fp = fdp->fd_ofiles[i];
2139 fdp->fd_ofiles[i] = NULL;
2140 fdp->fd_ofileflags[i] = 0;
2142 if (fp->f_type == DTYPE_MQUEUE)
2143 mq_fdclose(td, i, fp);
2144 FILEDESC_XUNLOCK(fdp);
2145 (void) closef(fp, td);
2146 FILEDESC_XLOCK(fdp);
2149 FILEDESC_XUNLOCK(fdp);
2153 * It is unsafe for set[ug]id processes to be started with file
2154 * descriptors 0..2 closed, as these descriptors are given implicit
2155 * significance in the Standard C library. fdcheckstd() will create a
2156 * descriptor referencing /dev/null for each of stdin, stdout, and
2157 * stderr that is not already open.
2160 fdcheckstd(struct thread *td)
2162 struct filedesc *fdp;
2163 register_t retval, save;
2164 int i, error, devnull;
2166 fdp = td->td_proc->p_fd;
2169 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2172 for (i = 0; i < 3; i++) {
2173 if (fdp->fd_ofiles[i] != NULL)
2176 save = td->td_retval[0];
2177 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2179 devnull = td->td_retval[0];
2180 td->td_retval[0] = save;
2183 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2185 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2194 * Internal form of close. Decrement reference count on file structure.
2195 * Note: td may be NULL when closing a file that was being passed in a
2198 * XXXRW: Giant is not required for the caller, but often will be held; this
2199 * makes it moderately likely the Giant will be recursed in the VFS case.
2202 closef(struct file *fp, struct thread *td)
2206 struct filedesc_to_leader *fdtol;
2207 struct filedesc *fdp;
2208 struct file *fp_object;
2211 * POSIX record locking dictates that any close releases ALL
2212 * locks owned by this process. This is handled by setting
2213 * a flag in the unlock to free ONLY locks obeying POSIX
2214 * semantics, and not to free BSD-style file locks.
2215 * If the descriptor was in a message, POSIX-style locks
2216 * aren't passed with the descriptor, and the thread pointer
2217 * will be NULL. Callers should be careful only to pass a
2218 * NULL thread pointer when there really is no owning
2219 * context that might have locks, or the locks will be
2222 * If this is a capability, we do lock processing under the underlying
2223 * node, not the capability itself.
2225 (void)cap_funwrap(fp, 0, &fp_object);
2226 if ((fp_object->f_type == DTYPE_VNODE) && (td != NULL)) {
2229 vp = fp_object->f_vnode;
2230 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2231 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2232 lf.l_whence = SEEK_SET;
2235 lf.l_type = F_UNLCK;
2236 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2237 F_UNLCK, &lf, F_POSIX);
2239 fdtol = td->td_proc->p_fdtol;
2240 if (fdtol != NULL) {
2242 * Handle special case where file descriptor table is
2243 * shared between multiple process leaders.
2245 fdp = td->td_proc->p_fd;
2246 FILEDESC_XLOCK(fdp);
2247 for (fdtol = fdtol->fdl_next;
2248 fdtol != td->td_proc->p_fdtol;
2249 fdtol = fdtol->fdl_next) {
2250 if ((fdtol->fdl_leader->p_flag &
2253 fdtol->fdl_holdcount++;
2254 FILEDESC_XUNLOCK(fdp);
2255 lf.l_whence = SEEK_SET;
2258 lf.l_type = F_UNLCK;
2259 vp = fp_object->f_vnode;
2260 (void) VOP_ADVLOCK(vp,
2261 (caddr_t)fdtol->fdl_leader,
2262 F_UNLCK, &lf, F_POSIX);
2263 FILEDESC_XLOCK(fdp);
2264 fdtol->fdl_holdcount--;
2265 if (fdtol->fdl_holdcount == 0 &&
2266 fdtol->fdl_wakeup != 0) {
2267 fdtol->fdl_wakeup = 0;
2271 FILEDESC_XUNLOCK(fdp);
2273 VFS_UNLOCK_GIANT(vfslocked);
2275 return (fdrop(fp, td));
2279 * Initialize the file pointer with the specified properties.
2281 * The ops are set with release semantics to be certain that the flags, type,
2282 * and data are visible when ops is. This is to prevent ops methods from being
2283 * called with bad data.
2286 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2291 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2295 fget_unlocked(struct filedesc *fdp, int fd)
2300 if (fd < 0 || fd >= fdp->fd_nfiles)
2303 * Fetch the descriptor locklessly. We avoid fdrop() races by
2304 * never raising a refcount above 0. To accomplish this we have
2305 * to use a cmpset loop rather than an atomic_add. The descriptor
2306 * must be re-verified once we acquire a reference to be certain
2307 * that the identity is still correct and we did not lose a race
2308 * due to preemption.
2311 fp = fdp->fd_ofiles[fd];
2314 count = fp->f_count;
2318 * Use an acquire barrier to prevent caching of fd_ofiles
2319 * so it is refreshed for verification.
2321 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2323 if (fp == fdp->fd_ofiles[fd])
2325 fdrop(fp, curthread);
2332 * Extract the file pointer associated with the specified descriptor for the
2333 * current user process.
2335 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2338 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2339 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2340 * Otherwise, if the file is a capability, its rights will be checked against
2341 * the capability rights mask, and if successful, the object will be unwrapped.
2343 * If an error occured the non-zero error is returned and *fpp is set to
2344 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2345 * responsible for fdrop().
2347 #define FGET_GETCAP 0x00000001
2349 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2350 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2353 struct filedesc *fdp;
2356 struct file *fp_fromcap;
2361 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2363 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2365 if (fp->f_ops == &badfileops) {
2372 * If this is a capability, what rights does it have?
2374 if (haverightsp != NULL) {
2375 if (fp->f_type == DTYPE_CAPABILITY)
2376 *haverightsp = cap_rights(fp);
2378 *haverightsp = CAP_MASK_VALID;
2382 * If a capability has been requested, return the capability directly.
2383 * Otherwise, check capability rights, extract the underlying object,
2384 * and check its access flags.
2386 if (fget_flags & FGET_GETCAP) {
2387 if (fp->f_type != DTYPE_CAPABILITY) {
2392 if (maxprotp == NULL)
2393 error = cap_funwrap(fp, needrights, &fp_fromcap);
2395 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2403 * If we've unwrapped a file, drop the original capability
2404 * and hold the new descriptor. fp after this point refers to
2405 * the actual (unwrapped) object, not the capability.
2407 if (fp != fp_fromcap) {
2413 #else /* !CAPABILITIES */
2414 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2415 ("%s: saw capability", __func__));
2416 if (maxprotp != NULL)
2417 *maxprotp = VM_PROT_ALL;
2418 #endif /* CAPABILITIES */
2421 * FREAD and FWRITE failure return EBADF as per POSIX.
2427 if ((fp->f_flag & flags) == 0)
2431 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2432 ((fp->f_flag & FWRITE) != 0))
2438 KASSERT(0, ("wrong flags"));
2451 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2454 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2458 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2462 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2466 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2469 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2473 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2476 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2480 * Unlike the other fget() calls, which accept and check capability rights
2481 * but never return capabilities, fgetcap() returns the capability but doesn't
2482 * check capability rights.
2485 fgetcap(struct thread *td, int fd, struct file **fpp)
2488 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2493 * Like fget() but loads the underlying vnode, or returns an error if the
2494 * descriptor does not represent a vnode. Note that pipes use vnodes but
2495 * never have VM objects. The returned vnode will be vref()'d.
2497 * XXX: what about the unused flags ?
2500 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2501 cap_rights_t *haverightsp, struct vnode **vpp)
2507 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2510 if (fp->f_vnode == NULL) {
2522 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2525 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2529 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2532 return (_fgetvp(td, fd, 0, need, have, vpp));
2536 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2539 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2543 fgetvp_exec(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2546 return (_fgetvp(td, fd, FEXEC, rights, NULL, vpp));
2551 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2555 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2560 * Like fget() but loads the underlying socket, or returns an error if the
2561 * descriptor does not represent a socket.
2563 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2566 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2567 * on their file descriptor reference to prevent the socket from being free'd
2571 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2580 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2582 if (fp->f_type != DTYPE_SOCKET) {
2587 *fflagp = fp->f_flag;
2598 * Drop the reference count on the socket and XXX release the SX lock in the
2599 * future. The last reference closes the socket.
2601 * Note: fputsock() is deprecated, see comment for fgetsock().
2604 fputsock(struct socket *so)
2609 CURVNET_SET(so->so_vnet);
2615 * Handle the last reference to a file being closed.
2617 * No special capability handling here, as the capability's fo_close will run
2618 * instead of the object here, and perform any necessary drop on the object.
2621 _fdrop(struct file *fp, struct thread *td)
2626 if (fp->f_count != 0)
2627 panic("fdrop: count %d", fp->f_count);
2628 if (fp->f_ops != &badfileops)
2629 error = fo_close(fp, td);
2630 atomic_subtract_int(&openfiles, 1);
2632 free(fp->f_advice, M_FADVISE);
2633 uma_zfree(file_zone, fp);
2639 * Apply an advisory lock on a file descriptor.
2641 * Just attempt to get a record lock of the requested type on the entire file
2642 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2644 #ifndef _SYS_SYSPROTO_H_
2652 sys_flock(struct thread *td, struct flock_args *uap)
2660 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2662 if (fp->f_type != DTYPE_VNODE) {
2664 return (EOPNOTSUPP);
2668 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2669 lf.l_whence = SEEK_SET;
2672 if (uap->how & LOCK_UN) {
2673 lf.l_type = F_UNLCK;
2674 atomic_clear_int(&fp->f_flag, FHASLOCK);
2675 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2678 if (uap->how & LOCK_EX)
2679 lf.l_type = F_WRLCK;
2680 else if (uap->how & LOCK_SH)
2681 lf.l_type = F_RDLCK;
2686 atomic_set_int(&fp->f_flag, FHASLOCK);
2687 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2688 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2691 VFS_UNLOCK_GIANT(vfslocked);
2695 * Duplicate the specified descriptor to a free descriptor.
2698 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2704 * If the to-be-dup'd fd number is greater than the allowed number
2705 * of file descriptors, or the fd to be dup'd has already been
2706 * closed, then reject.
2708 FILEDESC_XLOCK(fdp);
2709 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2710 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2711 FILEDESC_XUNLOCK(fdp);
2716 * There are two cases of interest here.
2718 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2720 * For ENXIO steal away the file structure from (dfd) and store it in
2721 * (indx). (dfd) is effectively closed by this operation.
2723 * Any other error code is just returned.
2728 * Check that the mode the file is being opened for is a
2729 * subset of the mode of the existing descriptor.
2731 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2732 FILEDESC_XUNLOCK(fdp);
2735 fp = fdp->fd_ofiles[indx];
2736 fdp->fd_ofiles[indx] = wfp;
2737 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2741 FILEDESC_XUNLOCK(fdp);
2744 * We now own the reference to fp that the ofiles[]
2745 * array used to own. Release it.
2752 * Steal away the file pointer from dfd and stuff it into indx.
2754 fp = fdp->fd_ofiles[indx];
2755 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2756 fdp->fd_ofiles[dfd] = NULL;
2757 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2758 fdp->fd_ofileflags[dfd] = 0;
2762 FILEDESC_XUNLOCK(fdp);
2765 * We now own the reference to fp that the ofiles[] array
2766 * used to own. Release it.
2773 FILEDESC_XUNLOCK(fdp);
2780 * Scan all active processes and prisons to see if any of them have a current
2781 * or root directory of `olddp'. If so, replace them with the new mount point.
2784 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2786 struct filedesc *fdp;
2791 if (vrefcnt(olddp) == 1)
2794 sx_slock(&allproc_lock);
2795 FOREACH_PROC_IN_SYSTEM(p) {
2799 FILEDESC_XLOCK(fdp);
2800 if (fdp->fd_cdir == olddp) {
2802 fdp->fd_cdir = newdp;
2805 if (fdp->fd_rdir == olddp) {
2807 fdp->fd_rdir = newdp;
2810 if (fdp->fd_jdir == olddp) {
2812 fdp->fd_jdir = newdp;
2815 FILEDESC_XUNLOCK(fdp);
2818 sx_sunlock(&allproc_lock);
2819 if (rootvnode == olddp) {
2824 mtx_lock(&prison0.pr_mtx);
2825 if (prison0.pr_root == olddp) {
2827 prison0.pr_root = newdp;
2830 mtx_unlock(&prison0.pr_mtx);
2831 sx_slock(&allprison_lock);
2832 TAILQ_FOREACH(pr, &allprison, pr_list) {
2833 mtx_lock(&pr->pr_mtx);
2834 if (pr->pr_root == olddp) {
2836 pr->pr_root = newdp;
2839 mtx_unlock(&pr->pr_mtx);
2841 sx_sunlock(&allprison_lock);
2846 struct filedesc_to_leader *
2847 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2849 struct filedesc_to_leader *fdtol;
2851 fdtol = malloc(sizeof(struct filedesc_to_leader),
2852 M_FILEDESC_TO_LEADER,
2854 fdtol->fdl_refcount = 1;
2855 fdtol->fdl_holdcount = 0;
2856 fdtol->fdl_wakeup = 0;
2857 fdtol->fdl_leader = leader;
2859 FILEDESC_XLOCK(fdp);
2860 fdtol->fdl_next = old->fdl_next;
2861 fdtol->fdl_prev = old;
2862 old->fdl_next = fdtol;
2863 fdtol->fdl_next->fdl_prev = fdtol;
2864 FILEDESC_XUNLOCK(fdp);
2866 fdtol->fdl_next = fdtol;
2867 fdtol->fdl_prev = fdtol;
2873 * Get file structures globally.
2876 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2879 struct filedesc *fdp;
2884 error = sysctl_wire_old_buffer(req, 0);
2887 if (req->oldptr == NULL) {
2889 sx_slock(&allproc_lock);
2890 FOREACH_PROC_IN_SYSTEM(p) {
2891 if (p->p_state == PRS_NEW)
2896 /* overestimates sparse tables. */
2897 if (fdp->fd_lastfile > 0)
2898 n += fdp->fd_lastfile;
2901 sx_sunlock(&allproc_lock);
2902 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2905 bzero(&xf, sizeof(xf));
2906 xf.xf_size = sizeof(xf);
2907 sx_slock(&allproc_lock);
2908 FOREACH_PROC_IN_SYSTEM(p) {
2910 if (p->p_state == PRS_NEW) {
2914 if (p_cansee(req->td, p) != 0) {
2918 xf.xf_pid = p->p_pid;
2919 xf.xf_uid = p->p_ucred->cr_uid;
2924 FILEDESC_SLOCK(fdp);
2925 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2926 if ((fp = fdp->fd_ofiles[n]) == NULL)
2930 xf.xf_data = fp->f_data;
2931 xf.xf_vnode = fp->f_vnode;
2932 xf.xf_type = fp->f_type;
2933 xf.xf_count = fp->f_count;
2935 xf.xf_offset = foffset_get(fp);
2936 xf.xf_flag = fp->f_flag;
2937 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2941 FILEDESC_SUNLOCK(fdp);
2946 sx_sunlock(&allproc_lock);
2950 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2951 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2953 #ifdef KINFO_OFILE_SIZE
2954 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2957 #ifdef COMPAT_FREEBSD7
2959 export_vnode_for_osysctl(struct vnode *vp, int type,
2960 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2963 char *fullpath, *freepath;
2966 bzero(kif, sizeof(*kif));
2967 kif->kf_structsize = sizeof(*kif);
2971 kif->kf_type = KF_TYPE_VNODE;
2972 /* This function only handles directories. */
2973 if (vp->v_type != VDIR) {
2977 kif->kf_vnode_type = KF_VTYPE_VDIR;
2980 * This is not a true file descriptor, so we set a bogus refcount
2981 * and offset to indicate these fields should be ignored.
2983 kif->kf_ref_count = -1;
2984 kif->kf_offset = -1;
2988 FILEDESC_SUNLOCK(fdp);
2989 vn_fullpath(curthread, vp, &fullpath, &freepath);
2990 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2992 VFS_UNLOCK_GIANT(vfslocked);
2993 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2994 if (freepath != NULL)
2995 free(freepath, M_TEMP);
2996 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2997 FILEDESC_SLOCK(fdp);
3002 * Get per-process file descriptors for use by procstat(1), et al.
3005 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3007 char *fullpath, *freepath;
3008 struct kinfo_ofile *kif;
3009 struct filedesc *fdp;
3010 int error, i, *name;
3011 struct shmfd *shmfd;
3021 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3028 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3029 FILEDESC_SLOCK(fdp);
3030 if (fdp->fd_cdir != NULL)
3031 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3033 if (fdp->fd_rdir != NULL)
3034 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3036 if (fdp->fd_jdir != NULL)
3037 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3039 for (i = 0; i < fdp->fd_nfiles; i++) {
3040 if ((fp = fdp->fd_ofiles[i]) == NULL)
3042 bzero(kif, sizeof(*kif));
3043 kif->kf_structsize = sizeof(*kif);
3053 * When reporting a capability, most fields will be from the
3054 * underlying object, but do mark as a capability. With
3055 * ofiledesc, we don't have a field to export the cap_rights_t,
3056 * but we do with the new filedesc.
3058 if (fp->f_type == DTYPE_CAPABILITY) {
3059 kif->kf_flags |= KF_FLAG_CAPABILITY;
3060 (void)cap_funwrap(fp, 0, &fp);
3063 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3064 ("sysctl_kern_proc_ofiledesc: saw capability"));
3066 switch (fp->f_type) {
3068 kif->kf_type = KF_TYPE_VNODE;
3073 kif->kf_type = KF_TYPE_SOCKET;
3078 kif->kf_type = KF_TYPE_PIPE;
3082 kif->kf_type = KF_TYPE_FIFO;
3087 kif->kf_type = KF_TYPE_KQUEUE;
3091 kif->kf_type = KF_TYPE_CRYPTO;
3095 kif->kf_type = KF_TYPE_MQUEUE;
3099 kif->kf_type = KF_TYPE_SHM;
3104 kif->kf_type = KF_TYPE_SEM;
3109 kif->kf_type = KF_TYPE_PTS;
3114 case DTYPE_PROCDESC:
3115 kif->kf_type = KF_TYPE_PROCDESC;
3120 kif->kf_type = KF_TYPE_UNKNOWN;
3123 kif->kf_ref_count = fp->f_count;
3124 if (fp->f_flag & FREAD)
3125 kif->kf_flags |= KF_FLAG_READ;
3126 if (fp->f_flag & FWRITE)
3127 kif->kf_flags |= KF_FLAG_WRITE;
3128 if (fp->f_flag & FAPPEND)
3129 kif->kf_flags |= KF_FLAG_APPEND;
3130 if (fp->f_flag & FASYNC)
3131 kif->kf_flags |= KF_FLAG_ASYNC;
3132 if (fp->f_flag & FFSYNC)
3133 kif->kf_flags |= KF_FLAG_FSYNC;
3134 if (fp->f_flag & FNONBLOCK)
3135 kif->kf_flags |= KF_FLAG_NONBLOCK;
3136 if (fp->f_flag & O_DIRECT)
3137 kif->kf_flags |= KF_FLAG_DIRECT;
3138 if (fp->f_flag & FHASLOCK)
3139 kif->kf_flags |= KF_FLAG_HASLOCK;
3140 kif->kf_offset = foffset_get(fp);
3143 switch (vp->v_type) {
3145 kif->kf_vnode_type = KF_VTYPE_VNON;
3148 kif->kf_vnode_type = KF_VTYPE_VREG;
3151 kif->kf_vnode_type = KF_VTYPE_VDIR;
3154 kif->kf_vnode_type = KF_VTYPE_VBLK;
3157 kif->kf_vnode_type = KF_VTYPE_VCHR;
3160 kif->kf_vnode_type = KF_VTYPE_VLNK;
3163 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3166 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3169 kif->kf_vnode_type = KF_VTYPE_VBAD;
3172 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3176 * It is OK to drop the filedesc lock here as we will
3177 * re-validate and re-evaluate its properties when
3178 * the loop continues.
3182 FILEDESC_SUNLOCK(fdp);
3183 vn_fullpath(curthread, vp, &fullpath, &freepath);
3184 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3186 VFS_UNLOCK_GIANT(vfslocked);
3187 strlcpy(kif->kf_path, fullpath,
3188 sizeof(kif->kf_path));
3189 if (freepath != NULL)
3190 free(freepath, M_TEMP);
3191 FILEDESC_SLOCK(fdp);
3194 struct sockaddr *sa;
3196 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3197 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3198 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3201 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3202 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3203 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3206 kif->kf_sock_domain =
3207 so->so_proto->pr_domain->dom_family;
3208 kif->kf_sock_type = so->so_type;
3209 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3212 strlcpy(kif->kf_path, tty_devname(tp),
3213 sizeof(kif->kf_path));
3216 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3217 if (ks != NULL && ksem_info != NULL)
3218 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3219 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3223 FILEDESC_SUNLOCK(fdp);
3229 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3230 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3231 #endif /* COMPAT_FREEBSD7 */
3233 #ifdef KINFO_FILE_SIZE
3234 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3238 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3239 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3240 struct kinfo_file *kif, struct sbuf *sb, ssize_t *remainder)
3245 } fflags_table[] = {
3246 { FAPPEND, KF_FLAG_APPEND },
3247 { FASYNC, KF_FLAG_ASYNC },
3248 { FFSYNC, KF_FLAG_FSYNC },
3249 { FHASLOCK, KF_FLAG_HASLOCK },
3250 { FNONBLOCK, KF_FLAG_NONBLOCK },
3251 { FREAD, KF_FLAG_READ },
3252 { FWRITE, KF_FLAG_WRITE },
3253 { O_CREAT, KF_FLAG_CREAT },
3254 { O_DIRECT, KF_FLAG_DIRECT },
3255 { O_EXCL, KF_FLAG_EXCL },
3256 { O_EXEC, KF_FLAG_EXEC },
3257 { O_EXLOCK, KF_FLAG_EXLOCK },
3258 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3259 { O_SHLOCK, KF_FLAG_SHLOCK },
3260 { O_TRUNC, KF_FLAG_TRUNC }
3262 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3264 int error, vfslocked;
3267 if (*remainder == 0)
3269 bzero(kif, sizeof(*kif));
3273 vp = (struct vnode *)data;
3274 error = fill_vnode_info(vp, kif);
3275 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3277 VFS_UNLOCK_GIANT(vfslocked);
3279 case KF_TYPE_SOCKET:
3280 error = fill_socket_info((struct socket *)data, kif);
3283 error = fill_pipe_info((struct pipe *)data, kif);
3286 error = fill_pts_info((struct tty *)data, kif);
3288 case KF_TYPE_PROCDESC:
3289 error = fill_procdesc_info((struct procdesc *)data, kif);
3292 error = fill_sem_info((struct file *)data, kif);
3295 error = fill_shm_info((struct file *)data, kif);
3301 kif->kf_status |= KF_ATTR_VALID;
3304 * Translate file access flags.
3306 for (i = 0; i < NFFLAGS; i++)
3307 if (fflags & fflags_table[i].fflag)
3308 kif->kf_flags |= fflags_table[i].kf_fflag;
3310 kif->kf_flags |= KF_FLAG_CAPABILITY;
3312 kif->kf_cap_rights = fd_cap_rights;
3314 kif->kf_type = type;
3315 kif->kf_ref_count = refcnt;
3316 kif->kf_offset = offset;
3317 /* Pack record size down */
3318 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3319 strlen(kif->kf_path) + 1;
3320 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3321 if (*remainder != -1) {
3322 if (*remainder < kif->kf_structsize) {
3323 /* Terminate export. */
3327 *remainder -= kif->kf_structsize;
3329 error = sbuf_bcat(sb, kif, kif->kf_structsize);
3334 * Store a process file descriptor information to sbuf.
3336 * Takes a locked proc as argument, and returns with the proc unlocked.
3339 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3342 struct filedesc *fdp;
3343 struct kinfo_file *kif;
3344 struct vnode *cttyvp, *textvp, *tracevp;
3349 int fd_is_cap, type, refcnt, fflags;
3350 cap_rights_t fd_cap_rights;
3352 PROC_LOCK_ASSERT(p, MA_OWNED);
3356 tracevp = p->p_tracevp;
3357 if (tracevp != NULL)
3360 textvp = p->p_textvp;
3363 /* Controlling tty. */
3365 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3366 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3372 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3373 if (tracevp != NULL)
3374 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3375 FREAD | FWRITE, -1, -1, 0, 0, kif, sb, &remainder);
3377 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3378 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3380 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3381 FREAD | FWRITE, -1, -1, 0, 0, kif, sb, &remainder);
3385 FILEDESC_SLOCK(fdp);
3386 /* working directory */
3387 if (fdp->fd_cdir != NULL) {
3389 data = fdp->fd_cdir;
3390 FILEDESC_SUNLOCK(fdp);
3391 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3392 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3393 FILEDESC_SLOCK(fdp);
3395 /* root directory */
3396 if (fdp->fd_rdir != NULL) {
3398 data = fdp->fd_rdir;
3399 FILEDESC_SUNLOCK(fdp);
3400 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3401 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3402 FILEDESC_SLOCK(fdp);
3404 /* jail directory */
3405 if (fdp->fd_jdir != NULL) {
3407 data = fdp->fd_jdir;
3408 FILEDESC_SUNLOCK(fdp);
3409 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3410 FREAD, -1, -1, 0, 0, kif, sb, &remainder);
3411 FILEDESC_SLOCK(fdp);
3413 for (i = 0; i < fdp->fd_nfiles; i++) {
3414 if ((fp = fdp->fd_ofiles[i]) == NULL)
3422 * When reporting a capability, most fields will be from the
3423 * underlying object, but do mark as a capability and export
3424 * the capability rights mask.
3426 if (fp->f_type == DTYPE_CAPABILITY) {
3428 fd_cap_rights = cap_rights(fp);
3429 (void)cap_funwrap(fp, 0, &fp);
3431 #else /* !CAPABILITIES */
3432 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3433 ("sysctl_kern_proc_filedesc: saw capability"));
3435 switch (fp->f_type) {
3437 type = KF_TYPE_VNODE;
3443 type = KF_TYPE_SOCKET;
3448 type = KF_TYPE_PIPE;
3453 type = KF_TYPE_FIFO;
3459 type = KF_TYPE_KQUEUE;
3463 type = KF_TYPE_CRYPTO;
3467 type = KF_TYPE_MQUEUE;
3486 case DTYPE_PROCDESC:
3487 type = KF_TYPE_PROCDESC;
3493 type = KF_TYPE_UNKNOWN;
3496 refcnt = fp->f_count;
3497 fflags = fp->f_flag;
3498 offset = foffset_get(fp);
3501 * Create sysctl entry.
3502 * It is OK to drop the filedesc lock here as we will
3503 * re-validate and re-evaluate its properties when
3504 * the loop continues.
3506 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3507 FILEDESC_SUNLOCK(fdp);
3508 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3509 offset, fd_is_cap, fd_cap_rights, kif, sb, &remainder);
3510 if (type == KF_TYPE_VNODE || type == KF_TYPE_FIFO)
3511 FILEDESC_SLOCK(fdp);
3515 FILEDESC_SUNLOCK(fdp);
3523 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3526 * Get per-process file descriptors for use by procstat(1), et al.
3529 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3534 int error, error2, *name;
3538 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3539 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3544 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3545 error = kern_proc_filedesc_out(p, &sb, maxlen);
3546 error2 = sbuf_finish(&sb);
3548 return (error != 0 ? error : error2);
3552 vntype_to_kinfo(int vtype)
3557 } vtypes_table[] = {
3558 { VBAD, KF_VTYPE_VBAD },
3559 { VBLK, KF_VTYPE_VBLK },
3560 { VCHR, KF_VTYPE_VCHR },
3561 { VDIR, KF_VTYPE_VDIR },
3562 { VFIFO, KF_VTYPE_VFIFO },
3563 { VLNK, KF_VTYPE_VLNK },
3564 { VNON, KF_VTYPE_VNON },
3565 { VREG, KF_VTYPE_VREG },
3566 { VSOCK, KF_VTYPE_VSOCK }
3568 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3572 * Perform vtype translation.
3574 for (i = 0; i < NVTYPES; i++)
3575 if (vtypes_table[i].vtype == vtype)
3578 return (vtypes_table[i].kf_vtype);
3580 return (KF_VTYPE_UNKNOWN);
3584 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3587 char *fullpath, *freepath;
3588 int error, vfslocked;
3592 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3595 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3597 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3599 if (freepath != NULL)
3600 free(freepath, M_TEMP);
3603 * Retrieve vnode attributes.
3605 va.va_fsid = VNOVAL;
3607 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3608 vn_lock(vp, LK_SHARED | LK_RETRY);
3609 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3611 VFS_UNLOCK_GIANT(vfslocked);
3614 if (va.va_fsid != VNOVAL)
3615 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3617 kif->kf_un.kf_file.kf_file_fsid =
3618 vp->v_mount->mnt_stat.f_fsid.val[0];
3619 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3620 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3621 kif->kf_un.kf_file.kf_file_size = va.va_size;
3622 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3627 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3629 struct sockaddr *sa;
3630 struct inpcb *inpcb;
3631 struct unpcb *unpcb;
3636 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3637 kif->kf_sock_type = so->so_type;
3638 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3639 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3640 switch(kif->kf_sock_domain) {
3643 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3644 if (so->so_pcb != NULL) {
3645 inpcb = (struct inpcb *)(so->so_pcb);
3646 kif->kf_un.kf_sock.kf_sock_inpcb =
3647 (uintptr_t)inpcb->inp_ppcb;
3652 if (so->so_pcb != NULL) {
3653 unpcb = (struct unpcb *)(so->so_pcb);
3654 if (unpcb->unp_conn) {
3655 kif->kf_un.kf_sock.kf_sock_unpconn =
3656 (uintptr_t)unpcb->unp_conn;
3657 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3658 so->so_rcv.sb_state;
3659 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3660 so->so_snd.sb_state;
3665 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3666 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3667 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3670 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3671 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3672 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3675 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3676 sizeof(kif->kf_path));
3681 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3686 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3687 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3692 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3697 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3698 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3699 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3704 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3709 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3714 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3720 if (fp->f_data == NULL)
3722 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3724 if (ksem_info == NULL)
3726 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3727 &kif->kf_un.kf_sem.kf_sem_value);
3728 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3733 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3739 if (fp->f_data == NULL)
3741 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3743 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3744 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3745 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3749 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3750 sysctl_kern_proc_filedesc, "Process filedesc entries");
3754 * For the purposes of debugging, generate a human-readable string for the
3758 file_type_to_name(short type)
3788 * For the purposes of debugging, identify a process (if any, perhaps one of
3789 * many) that references the passed file in its file descriptor array. Return
3792 static struct proc *
3793 file_to_first_proc(struct file *fp)
3795 struct filedesc *fdp;
3799 FOREACH_PROC_IN_SYSTEM(p) {
3800 if (p->p_state == PRS_NEW)
3805 for (n = 0; n < fdp->fd_nfiles; n++) {
3806 if (fp == fdp->fd_ofiles[n])
3814 db_print_file(struct file *fp, int header)
3819 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3820 "File", "Type", "Data", "Flag", "GCFl", "Count",
3821 "MCount", "Vnode", "FPID", "FCmd");
3822 p = file_to_first_proc(fp);
3823 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3824 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3825 0, fp->f_count, 0, fp->f_vnode,
3826 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3829 DB_SHOW_COMMAND(file, db_show_file)
3834 db_printf("usage: show file <addr>\n");
3837 fp = (struct file *)addr;
3838 db_print_file(fp, 1);
3841 DB_SHOW_COMMAND(files, db_show_files)
3843 struct filedesc *fdp;
3850 FOREACH_PROC_IN_SYSTEM(p) {
3851 if (p->p_state == PRS_NEW)
3853 if ((fdp = p->p_fd) == NULL)
3855 for (n = 0; n < fdp->fd_nfiles; ++n) {
3856 if ((fp = fdp->fd_ofiles[n]) == NULL)
3858 db_print_file(fp, header);
3865 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3866 &maxfilesperproc, 0, "Maximum files allowed open per process");
3868 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3869 &maxfiles, 0, "Maximum number of files");
3871 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3872 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3876 filelistinit(void *dummy)
3879 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3880 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3881 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3882 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3884 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3886 /*-------------------------------------------------------------------*/
3889 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3890 int flags, struct thread *td)
3897 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3905 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3913 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3921 badfo_kqfilter(struct file *fp, struct knote *kn)
3928 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3936 badfo_close(struct file *fp, struct thread *td)
3943 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3951 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3958 struct fileops badfileops = {
3959 .fo_read = badfo_readwrite,
3960 .fo_write = badfo_readwrite,
3961 .fo_truncate = badfo_truncate,
3962 .fo_ioctl = badfo_ioctl,
3963 .fo_poll = badfo_poll,
3964 .fo_kqfilter = badfo_kqfilter,
3965 .fo_stat = badfo_stat,
3966 .fo_close = badfo_close,
3967 .fo_chmod = badfo_chmod,
3968 .fo_chown = badfo_chown,
3972 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3980 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3987 /*-------------------------------------------------------------------*/
3990 * File Descriptor pseudo-device driver (/dev/fd/).
3992 * Opening minor device N dup()s the file (if any) connected to file
3993 * descriptor N belonging to the calling process. Note that this driver
3994 * consists of only the ``open()'' routine, because all subsequent
3995 * references to this file will be direct to the other driver.
3997 * XXX: we could give this one a cloning event handler if necessary.
4002 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4006 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4007 * the file descriptor being sought for duplication. The error
4008 * return ensures that the vnode for this device will be released
4009 * by vn_open. Open will detect this special error and take the
4010 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4011 * will simply report the error.
4013 td->td_dupfd = dev2unit(dev);
4017 static struct cdevsw fildesc_cdevsw = {
4018 .d_version = D_VERSION,
4024 fildesc_drvinit(void *unused)
4028 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4029 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4030 make_dev_alias(dev, "stdin");
4031 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4032 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4033 make_dev_alias(dev, "stdout");
4034 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4035 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4036 make_dev_alias(dev, "stderr");
4039 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);