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);
136 static int getmaxfd(struct proc *p);
139 * A process is initially started out with NDFILE descriptors stored within
140 * this structure, selected to be enough for typical applications based on
141 * the historical limit of 20 open files (and the usage of descriptors by
142 * shells). If these descriptors are exhausted, a larger descriptor table
143 * may be allocated, up to a process' resource limit; the internal arrays
147 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
148 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
149 #define NDSLOT(x) ((x) / NDENTRIES)
150 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
151 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
154 * Storage required per open file descriptor.
156 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
159 * Storage to hold unused ofiles that need to be reclaimed.
162 struct file **ft_table;
163 SLIST_ENTRY(freetable) ft_next;
167 * Basic allocation of descriptors:
168 * one of the above, plus arrays for NDFILE descriptors.
171 struct filedesc fd_fd;
173 * ofiles which need to be reclaimed on free.
175 SLIST_HEAD(,freetable) fd_free;
177 * These arrays are used when the number of open files is
178 * <= NDFILE, and are then pointed to by the pointers above.
180 struct file *fd_dfiles[NDFILE];
181 char fd_dfileflags[NDFILE];
182 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
186 * Descriptor management.
188 volatile int openfiles; /* actual number of open files */
189 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
190 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
192 /* A mutex to protect the association between a proc and filedesc. */
193 static struct mtx fdesc_mtx;
196 * Find the first zero bit in the given bitmap, starting at low and not
197 * exceeding size - 1.
200 fd_first_free(struct filedesc *fdp, int low, int size)
202 NDSLOTTYPE *map = fdp->fd_map;
210 if (low % NDENTRIES) {
211 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
212 if ((mask &= ~map[off]) != 0UL)
213 return (off * NDENTRIES + ffsl(mask) - 1);
216 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
217 if (map[off] != ~0UL)
218 return (off * NDENTRIES + ffsl(~map[off]) - 1);
223 * Find the highest non-zero bit in the given bitmap, starting at low and
224 * not exceeding size - 1.
227 fd_last_used(struct filedesc *fdp, int low, int size)
229 NDSLOTTYPE *map = fdp->fd_map;
237 if (size % NDENTRIES) {
238 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
239 if ((mask &= map[off]) != 0)
240 return (off * NDENTRIES + flsl(mask) - 1);
243 for (minoff = NDSLOT(low); off >= minoff; --off)
245 return (off * NDENTRIES + flsl(map[off]) - 1);
250 fdisused(struct filedesc *fdp, int fd)
252 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
253 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
254 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
258 * Mark a file descriptor as used.
261 fdused(struct filedesc *fdp, int fd)
264 FILEDESC_XLOCK_ASSERT(fdp);
265 KASSERT(!fdisused(fdp, fd),
266 ("fd already used"));
268 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
269 if (fd > fdp->fd_lastfile)
270 fdp->fd_lastfile = fd;
271 if (fd == fdp->fd_freefile)
272 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
276 * Mark a file descriptor as unused.
279 fdunused(struct filedesc *fdp, int fd)
282 FILEDESC_XLOCK_ASSERT(fdp);
283 KASSERT(fdisused(fdp, fd),
284 ("fd is already unused"));
285 KASSERT(fdp->fd_ofiles[fd] == NULL,
286 ("fd is still in use"));
288 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
289 if (fd < fdp->fd_freefile)
290 fdp->fd_freefile = fd;
291 if (fd == fdp->fd_lastfile)
292 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
296 * System calls on descriptors.
298 #ifndef _SYS_SYSPROTO_H_
299 struct getdtablesize_args {
305 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
307 struct proc *p = td->td_proc;
312 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
313 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
315 if (lim < td->td_retval[0])
316 td->td_retval[0] = lim;
321 * Duplicate a file descriptor to a particular value.
323 * Note: keep in mind that a potential race condition exists when closing
324 * descriptors from a shared descriptor table (via rfork).
326 #ifndef _SYS_SYSPROTO_H_
334 sys_dup2(struct thread *td, struct dup2_args *uap)
337 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
342 * Duplicate a file descriptor.
344 #ifndef _SYS_SYSPROTO_H_
351 sys_dup(struct thread *td, struct dup_args *uap)
354 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
358 * The file control system call.
360 #ifndef _SYS_SYSPROTO_H_
369 sys_fcntl(struct thread *td, struct fcntl_args *uap)
384 * Convert old flock structure to new.
386 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
387 fl.l_start = ofl.l_start;
388 fl.l_len = ofl.l_len;
389 fl.l_pid = ofl.l_pid;
390 fl.l_type = ofl.l_type;
391 fl.l_whence = ofl.l_whence;
411 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
420 error = kern_fcntl(td, uap->fd, cmd, arg);
423 if (uap->cmd == F_OGETLK) {
424 ofl.l_start = fl.l_start;
425 ofl.l_len = fl.l_len;
426 ofl.l_pid = fl.l_pid;
427 ofl.l_type = fl.l_type;
428 ofl.l_whence = fl.l_whence;
429 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
430 } else if (uap->cmd == F_GETLK) {
431 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
436 static inline struct file *
437 fdtofp(int fd, struct filedesc *fdp)
441 FILEDESC_LOCK_ASSERT(fdp);
442 if ((unsigned)fd >= fdp->fd_nfiles ||
443 (fp = fdp->fd_ofiles[fd]) == NULL)
449 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
452 *fpp = fdtofp(fd, fdp);
457 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
458 int err = cap_funwrap(*fpp, rights, fpp);
464 #endif /* CAPABILITIES */
469 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
471 struct filedesc *fdp;
492 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
495 case F_DUPFD_CLOEXEC:
497 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
503 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
506 case F_DUP2FD_CLOEXEC:
508 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
514 if ((fp = fdtofp(fd, fdp)) == NULL) {
515 FILEDESC_SUNLOCK(fdp);
519 pop = &fdp->fd_ofileflags[fd];
520 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
521 FILEDESC_SUNLOCK(fdp);
526 if ((fp = fdtofp(fd, fdp)) == NULL) {
527 FILEDESC_XUNLOCK(fdp);
531 pop = &fdp->fd_ofileflags[fd];
532 *pop = (*pop &~ UF_EXCLOSE) |
533 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
534 FILEDESC_XUNLOCK(fdp);
539 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
541 FILEDESC_SUNLOCK(fdp);
544 td->td_retval[0] = OFLAGS(fp->f_flag);
545 FILEDESC_SUNLOCK(fdp);
550 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
552 FILEDESC_SUNLOCK(fdp);
556 FILEDESC_SUNLOCK(fdp);
558 tmp = flg = fp->f_flag;
560 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
561 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
562 tmp = fp->f_flag & FNONBLOCK;
563 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
568 tmp = fp->f_flag & FASYNC;
569 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
574 atomic_clear_int(&fp->f_flag, FNONBLOCK);
576 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
582 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
584 FILEDESC_SUNLOCK(fdp);
588 FILEDESC_SUNLOCK(fdp);
589 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
591 td->td_retval[0] = tmp;
597 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
599 FILEDESC_SUNLOCK(fdp);
603 FILEDESC_SUNLOCK(fdp);
605 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
610 error = priv_check(td, PRIV_NFS_LOCKD);
618 /* FALLTHROUGH F_SETLK */
623 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
625 FILEDESC_SUNLOCK(fdp);
628 if (fp->f_type != DTYPE_VNODE) {
629 FILEDESC_SUNLOCK(fdp);
633 flp = (struct flock *)arg;
634 if (flp->l_whence == SEEK_CUR) {
635 foffset = foffset_get(fp);
638 foffset > OFF_MAX - flp->l_start)) {
639 FILEDESC_SUNLOCK(fdp);
643 flp->l_start += foffset;
647 * VOP_ADVLOCK() may block.
650 FILEDESC_SUNLOCK(fdp);
652 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
653 switch (flp->l_type) {
655 if ((fp->f_flag & FREAD) == 0) {
659 PROC_LOCK(p->p_leader);
660 p->p_leader->p_flag |= P_ADVLOCK;
661 PROC_UNLOCK(p->p_leader);
662 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
666 if ((fp->f_flag & FWRITE) == 0) {
670 PROC_LOCK(p->p_leader);
671 p->p_leader->p_flag |= P_ADVLOCK;
672 PROC_UNLOCK(p->p_leader);
673 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
677 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
682 * Temporary api for testing remote lock
685 if (flg != F_REMOTE) {
689 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
690 F_UNLCKSYS, flp, flg);
696 VFS_UNLOCK_GIANT(vfslocked);
698 /* Check for race with close */
700 if ((unsigned) fd >= fdp->fd_nfiles ||
701 fp != fdp->fd_ofiles[fd]) {
702 FILEDESC_SUNLOCK(fdp);
703 flp->l_whence = SEEK_SET;
706 flp->l_type = F_UNLCK;
707 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
708 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
709 F_UNLCK, flp, F_POSIX);
710 VFS_UNLOCK_GIANT(vfslocked);
713 FILEDESC_SUNLOCK(fdp);
719 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
721 FILEDESC_SUNLOCK(fdp);
724 if (fp->f_type != DTYPE_VNODE) {
725 FILEDESC_SUNLOCK(fdp);
729 flp = (struct flock *)arg;
730 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
731 flp->l_type != F_UNLCK) {
732 FILEDESC_SUNLOCK(fdp);
736 if (flp->l_whence == SEEK_CUR) {
737 foffset = foffset_get(fp);
738 if ((flp->l_start > 0 &&
739 foffset > OFF_MAX - flp->l_start) ||
741 foffset < OFF_MIN - flp->l_start)) {
742 FILEDESC_SUNLOCK(fdp);
746 flp->l_start += foffset;
749 * VOP_ADVLOCK() may block.
752 FILEDESC_SUNLOCK(fdp);
754 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
755 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
757 VFS_UNLOCK_GIANT(vfslocked);
763 arg = arg ? 128 * 1024: 0;
767 if ((fp = fdtofp(fd, fdp)) == NULL) {
768 FILEDESC_SUNLOCK(fdp);
772 if (fp->f_type != DTYPE_VNODE) {
773 FILEDESC_SUNLOCK(fdp);
778 FILEDESC_SUNLOCK(fdp);
781 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
782 error = vn_lock(vp, LK_SHARED);
784 goto readahead_vnlock_fail;
785 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
787 fp->f_seqcount = (arg + bsize - 1) / bsize;
789 new = old = fp->f_flag;
791 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
792 readahead_vnlock_fail:
793 VFS_UNLOCK_GIANT(vfslocked);
797 new = old = fp->f_flag;
799 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
808 VFS_UNLOCK_GIANT(vfslocked);
813 getmaxfd(struct proc *p)
818 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
825 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
828 do_dup(struct thread *td, int flags, int old, int new,
831 struct filedesc *fdp;
835 int error, holdleaders, maxfd;
841 * Verify we have a valid descriptor to dup from and possibly to
842 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
843 * return EINVAL when the new descriptor is out of bounds.
848 return (flags & DUP_FCNTL ? EINVAL : EBADF);
851 return (flags & DUP_FCNTL ? EINVAL : EBADF);
854 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
855 FILEDESC_XUNLOCK(fdp);
858 if (flags & DUP_FIXED && old == new) {
860 if (flags & DUP_CLOEXEC)
861 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
862 FILEDESC_XUNLOCK(fdp);
865 fp = fdp->fd_ofiles[old];
869 * If the caller specified a file descriptor, make sure the file
870 * table is large enough to hold it, and grab it. Otherwise, just
871 * allocate a new descriptor the usual way. Since the filedesc
872 * lock may be temporarily dropped in the process, we have to look
875 if (flags & DUP_FIXED) {
876 if (new >= fdp->fd_nfiles) {
878 * The resource limits are here instead of e.g.
879 * fdalloc(), because the file descriptor table may be
880 * shared between processes, so we can't really use
881 * racct_add()/racct_sub(). Instead of counting the
882 * number of actually allocated descriptors, just put
883 * the limit on the size of the file descriptor table.
887 error = racct_set(p, RACCT_NOFILE, new + 1);
890 FILEDESC_XUNLOCK(fdp);
895 fdgrowtable(fdp, new + 1);
897 if (fdp->fd_ofiles[new] == NULL)
900 if ((error = fdalloc(td, new, &new)) != 0) {
901 FILEDESC_XUNLOCK(fdp);
908 * If the old file changed out from under us then treat it as a
909 * bad file descriptor. Userland should do its own locking to
912 if (fdp->fd_ofiles[old] != fp) {
913 /* we've allocated a descriptor which we won't use */
914 if (fdp->fd_ofiles[new] == NULL)
916 FILEDESC_XUNLOCK(fdp);
921 ("new fd is same as old"));
924 * Save info on the descriptor being overwritten. We cannot close
925 * it without introducing an ownership race for the slot, since we
926 * need to drop the filedesc lock to call closef().
928 * XXX this duplicates parts of close().
930 delfp = fdp->fd_ofiles[new];
933 if (td->td_proc->p_fdtol != NULL) {
935 * Ask fdfree() to sleep to ensure that all relevant
936 * process leaders can be traversed in closef().
938 fdp->fd_holdleaderscount++;
944 * Duplicate the source descriptor
946 fdp->fd_ofiles[new] = fp;
947 if ((flags & DUP_CLOEXEC) != 0)
948 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
950 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
951 if (new > fdp->fd_lastfile)
952 fdp->fd_lastfile = new;
956 * If we dup'd over a valid file, we now own the reference to it
957 * and must dispose of it using closef() semantics (as if a
958 * close() were performed on it).
960 * XXX this duplicates parts of close().
963 knote_fdclose(td, new);
964 if (delfp->f_type == DTYPE_MQUEUE)
965 mq_fdclose(td, new, delfp);
966 FILEDESC_XUNLOCK(fdp);
967 (void) closef(delfp, td);
970 fdp->fd_holdleaderscount--;
971 if (fdp->fd_holdleaderscount == 0 &&
972 fdp->fd_holdleaderswakeup != 0) {
973 fdp->fd_holdleaderswakeup = 0;
974 wakeup(&fdp->fd_holdleaderscount);
976 FILEDESC_XUNLOCK(fdp);
979 FILEDESC_XUNLOCK(fdp);
985 * If sigio is on the list associated with a process or process group,
986 * disable signalling from the device, remove sigio from the list and
990 funsetown(struct sigio **sigiop)
1000 *(sigio->sio_myref) = NULL;
1001 if ((sigio)->sio_pgid < 0) {
1002 struct pgrp *pg = (sigio)->sio_pgrp;
1004 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
1005 sigio, sio_pgsigio);
1008 struct proc *p = (sigio)->sio_proc;
1010 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1011 sigio, sio_pgsigio);
1015 crfree(sigio->sio_ucred);
1016 free(sigio, M_SIGIO);
1020 * Free a list of sigio structures.
1021 * We only need to lock the SIGIO_LOCK because we have made ourselves
1022 * inaccessible to callers of fsetown and therefore do not need to lock
1023 * the proc or pgrp struct for the list manipulation.
1026 funsetownlst(struct sigiolst *sigiolst)
1030 struct sigio *sigio;
1032 sigio = SLIST_FIRST(sigiolst);
1039 * Every entry of the list should belong
1040 * to a single proc or pgrp.
1042 if (sigio->sio_pgid < 0) {
1043 pg = sigio->sio_pgrp;
1044 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1045 } else /* if (sigio->sio_pgid > 0) */ {
1046 p = sigio->sio_proc;
1047 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1051 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1052 *(sigio->sio_myref) = NULL;
1054 KASSERT(sigio->sio_pgid < 0,
1055 ("Proc sigio in pgrp sigio list"));
1056 KASSERT(sigio->sio_pgrp == pg,
1057 ("Bogus pgrp in sigio list"));
1059 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1062 } else /* if (p != NULL) */ {
1063 KASSERT(sigio->sio_pgid > 0,
1064 ("Pgrp sigio in proc sigio list"));
1065 KASSERT(sigio->sio_proc == p,
1066 ("Bogus proc in sigio list"));
1068 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1073 crfree(sigio->sio_ucred);
1074 free(sigio, M_SIGIO);
1081 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1083 * After permission checking, add a sigio structure to the sigio list for
1084 * the process or process group.
1087 fsetown(pid_t pgid, struct sigio **sigiop)
1091 struct sigio *sigio;
1101 /* Allocate and fill in the new sigio out of locks. */
1102 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1103 sigio->sio_pgid = pgid;
1104 sigio->sio_ucred = crhold(curthread->td_ucred);
1105 sigio->sio_myref = sigiop;
1107 sx_slock(&proctree_lock);
1116 * Policy - Don't allow a process to FSETOWN a process
1117 * in another session.
1119 * Remove this test to allow maximum flexibility or
1120 * restrict FSETOWN to the current process or process
1121 * group for maximum safety.
1124 if (proc->p_session != curthread->td_proc->p_session) {
1130 } else /* if (pgid < 0) */ {
1131 pgrp = pgfind(-pgid);
1139 * Policy - Don't allow a process to FSETOWN a process
1140 * in another session.
1142 * Remove this test to allow maximum flexibility or
1143 * restrict FSETOWN to the current process or process
1144 * group for maximum safety.
1146 if (pgrp->pg_session != curthread->td_proc->p_session) {
1157 * Since funsetownlst() is called without the proctree
1158 * locked, we need to check for P_WEXIT.
1159 * XXX: is ESRCH correct?
1161 if ((proc->p_flag & P_WEXIT) != 0) {
1166 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1167 sigio->sio_proc = proc;
1171 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1172 sigio->sio_pgrp = pgrp;
1175 sx_sunlock(&proctree_lock);
1182 sx_sunlock(&proctree_lock);
1183 crfree(sigio->sio_ucred);
1184 free(sigio, M_SIGIO);
1189 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1193 struct sigio **sigiop;
1198 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1204 * Close a file descriptor.
1206 #ifndef _SYS_SYSPROTO_H_
1215 struct close_args *uap;
1218 return (kern_close(td, uap->fd));
1226 struct filedesc *fdp;
1227 struct file *fp, *fp_object;
1233 fdp = td->td_proc->p_fd;
1235 AUDIT_SYSCLOSE(td, fd);
1237 FILEDESC_XLOCK(fdp);
1238 if ((unsigned)fd >= fdp->fd_nfiles ||
1239 (fp = fdp->fd_ofiles[fd]) == NULL) {
1240 FILEDESC_XUNLOCK(fdp);
1243 fdp->fd_ofiles[fd] = NULL;
1244 fdp->fd_ofileflags[fd] = 0;
1246 if (td->td_proc->p_fdtol != NULL) {
1248 * Ask fdfree() to sleep to ensure that all relevant
1249 * process leaders can be traversed in closef().
1251 fdp->fd_holdleaderscount++;
1256 * We now hold the fp reference that used to be owned by the
1257 * descriptor array. We have to unlock the FILEDESC *AFTER*
1258 * knote_fdclose to prevent a race of the fd getting opened, a knote
1259 * added, and deleteing a knote for the new fd.
1261 knote_fdclose(td, fd);
1264 * When we're closing an fd with a capability, we need to notify
1265 * mqueue if the underlying object is of type mqueue.
1267 (void)cap_funwrap(fp, 0, &fp_object);
1268 if (fp_object->f_type == DTYPE_MQUEUE)
1269 mq_fdclose(td, fd, fp_object);
1270 FILEDESC_XUNLOCK(fdp);
1272 error = closef(fp, td);
1274 FILEDESC_XLOCK(fdp);
1275 fdp->fd_holdleaderscount--;
1276 if (fdp->fd_holdleaderscount == 0 &&
1277 fdp->fd_holdleaderswakeup != 0) {
1278 fdp->fd_holdleaderswakeup = 0;
1279 wakeup(&fdp->fd_holdleaderscount);
1281 FILEDESC_XUNLOCK(fdp);
1287 * Close open file descriptors.
1289 #ifndef _SYS_SYSPROTO_H_
1290 struct closefrom_args {
1296 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1298 struct filedesc *fdp;
1301 fdp = td->td_proc->p_fd;
1302 AUDIT_ARG_FD(uap->lowfd);
1305 * Treat negative starting file descriptor values identical to
1306 * closefrom(0) which closes all files.
1310 FILEDESC_SLOCK(fdp);
1311 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1312 if (fdp->fd_ofiles[fd] != NULL) {
1313 FILEDESC_SUNLOCK(fdp);
1314 (void)kern_close(td, fd);
1315 FILEDESC_SLOCK(fdp);
1318 FILEDESC_SUNLOCK(fdp);
1322 #if defined(COMPAT_43)
1324 * Return status information about a file descriptor.
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct ofstat_args {
1334 ofstat(struct thread *td, struct ofstat_args *uap)
1340 error = kern_fstat(td, uap->fd, &ub);
1343 error = copyout(&oub, uap->sb, sizeof(oub));
1347 #endif /* COMPAT_43 */
1350 * Return status information about a file descriptor.
1352 #ifndef _SYS_SYSPROTO_H_
1360 sys_fstat(struct thread *td, struct fstat_args *uap)
1365 error = kern_fstat(td, uap->fd, &ub);
1367 error = copyout(&ub, uap->sb, sizeof(ub));
1372 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1379 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1382 AUDIT_ARG_FILE(td->td_proc, fp);
1384 error = fo_stat(fp, sbp, td->td_ucred, td);
1387 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1394 * Return status information about a file descriptor.
1396 #ifndef _SYS_SYSPROTO_H_
1397 struct nfstat_args {
1404 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1410 error = kern_fstat(td, uap->fd, &ub);
1412 cvtnstat(&ub, &nub);
1413 error = copyout(&nub, uap->sb, sizeof(nub));
1419 * Return pathconf information about a file descriptor.
1421 #ifndef _SYS_SYSPROTO_H_
1422 struct fpathconf_args {
1429 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1435 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1438 /* If asynchronous I/O is available, it works for all descriptors. */
1439 if (uap->name == _PC_ASYNC_IO) {
1440 td->td_retval[0] = async_io_version;
1446 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1447 vn_lock(vp, LK_SHARED | LK_RETRY);
1448 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1450 VFS_UNLOCK_GIANT(vfslocked);
1451 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1452 if (uap->name != _PC_PIPE_BUF) {
1455 td->td_retval[0] = PIPE_BUF;
1467 * Grow the file table to accomodate (at least) nfd descriptors. This may
1468 * block and drop the filedesc lock, but it will reacquire it before
1472 fdgrowtable(struct filedesc *fdp, int nfd)
1474 struct filedesc0 *fdp0;
1475 struct freetable *fo;
1476 struct file **ntable;
1477 struct file **otable;
1479 int nnfiles, onfiles;
1482 FILEDESC_XLOCK_ASSERT(fdp);
1484 KASSERT(fdp->fd_nfiles > 0,
1485 ("zero-length file table"));
1487 /* compute the size of the new table */
1488 onfiles = fdp->fd_nfiles;
1489 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1490 if (nnfiles <= onfiles)
1491 /* the table is already large enough */
1494 /* allocate a new table and (if required) new bitmaps */
1495 FILEDESC_XUNLOCK(fdp);
1496 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1497 M_FILEDESC, M_ZERO | M_WAITOK);
1498 nfileflags = (char *)&ntable[nnfiles];
1499 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1500 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1501 M_FILEDESC, M_ZERO | M_WAITOK);
1504 FILEDESC_XLOCK(fdp);
1507 * We now have new tables ready to go. Since we dropped the
1508 * filedesc lock to call malloc(), watch out for a race.
1510 onfiles = fdp->fd_nfiles;
1511 if (onfiles >= nnfiles) {
1512 /* we lost the race, but that's OK */
1513 free(ntable, M_FILEDESC);
1515 free(nmap, M_FILEDESC);
1518 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1519 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1520 otable = fdp->fd_ofiles;
1521 fdp->fd_ofileflags = nfileflags;
1522 fdp->fd_ofiles = ntable;
1524 * We must preserve ofiles until the process exits because we can't
1525 * be certain that no threads have references to the old table via
1528 if (onfiles > NDFILE) {
1529 fo = (struct freetable *)&otable[onfiles];
1530 fdp0 = (struct filedesc0 *)fdp;
1531 fo->ft_table = otable;
1532 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1534 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1535 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1536 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1537 free(fdp->fd_map, M_FILEDESC);
1540 fdp->fd_nfiles = nnfiles;
1544 * Allocate a file descriptor for the process.
1547 fdalloc(struct thread *td, int minfd, int *result)
1549 struct proc *p = td->td_proc;
1550 struct filedesc *fdp = p->p_fd;
1556 FILEDESC_XLOCK_ASSERT(fdp);
1558 if (fdp->fd_freefile > minfd)
1559 minfd = fdp->fd_freefile;
1561 maxfd = getmaxfd(p);
1564 * Search the bitmap for a free descriptor. If none is found, try
1565 * to grow the file table. Keep at it until we either get a file
1566 * descriptor or run into process or system limits; fdgrowtable()
1567 * may drop the filedesc lock, so we're in a race.
1570 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1573 if (fd < fdp->fd_nfiles)
1577 error = racct_set(p, RACCT_NOFILE, min(fdp->fd_nfiles * 2, maxfd));
1582 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1586 * Perform some sanity checks, then mark the file descriptor as
1587 * used and return it to the caller.
1589 KASSERT(!fdisused(fdp, fd),
1590 ("fd_first_free() returned non-free descriptor"));
1591 KASSERT(fdp->fd_ofiles[fd] == NULL,
1592 ("free descriptor isn't"));
1593 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1600 * Allocate n file descriptors for the process.
1603 fdallocn(struct thread *td, int minfd, int *fds, int n)
1605 struct proc *p = td->td_proc;
1606 struct filedesc *fdp = p->p_fd;
1609 FILEDESC_XLOCK_ASSERT(fdp);
1611 if (!fdavail(td, n))
1614 for (i = 0; i < n; i++)
1615 if (fdalloc(td, 0, &fds[i]) != 0)
1619 for (i--; i >= 0; i--)
1620 fdunused(fdp, fds[i]);
1628 * Check to see whether n user file descriptors are available to the process
1632 fdavail(struct thread *td, int n)
1634 struct proc *p = td->td_proc;
1635 struct filedesc *fdp = td->td_proc->p_fd;
1639 FILEDESC_LOCK_ASSERT(fdp);
1642 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1643 * call racct_add() from there instead of dealing with containers
1647 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1649 last = min(fdp->fd_nfiles, lim);
1650 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1651 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1652 if (*fpp == NULL && --n <= 0)
1659 * Create a new open file structure and allocate a file decriptor for the
1660 * process that refers to it. We add one reference to the file for the
1661 * descriptor table and one reference for resultfp. This is to prevent us
1662 * being preempted and the entry in the descriptor table closed after we
1663 * release the FILEDESC lock.
1666 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1671 error = falloc_noinstall(td, &fp);
1673 return (error); /* no reference held on error */
1675 error = finstall(td, fp, &fd, flags);
1677 fdrop(fp, td); /* one reference (fp only) */
1681 if (resultfp != NULL)
1682 *resultfp = fp; /* copy out result */
1684 fdrop(fp, td); /* release local reference */
1686 if (resultfd != NULL)
1693 * Create a new open file structure without allocating a file descriptor.
1696 falloc_noinstall(struct thread *td, struct file **resultfp)
1699 int maxuserfiles = maxfiles - (maxfiles / 20);
1700 static struct timeval lastfail;
1703 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1705 if ((openfiles >= maxuserfiles &&
1706 priv_check(td, PRIV_MAXFILES) != 0) ||
1707 openfiles >= maxfiles) {
1708 if (ppsratecheck(&lastfail, &curfail, 1)) {
1709 printf("kern.maxfiles limit exceeded by uid %i, "
1710 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1714 atomic_add_int(&openfiles, 1);
1715 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1716 refcount_init(&fp->f_count, 1);
1717 fp->f_cred = crhold(td->td_ucred);
1718 fp->f_ops = &badfileops;
1726 * Install a file in a file descriptor table.
1729 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1731 struct filedesc *fdp = td->td_proc->p_fd;
1734 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1735 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1737 FILEDESC_XLOCK(fdp);
1738 if ((error = fdalloc(td, 0, fd))) {
1739 FILEDESC_XUNLOCK(fdp);
1743 fdp->fd_ofiles[*fd] = fp;
1744 if ((flags & O_CLOEXEC) != 0)
1745 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1746 FILEDESC_XUNLOCK(fdp);
1751 * Build a new filedesc structure from another.
1752 * Copy the current, root, and jail root vnode references.
1755 fdinit(struct filedesc *fdp)
1757 struct filedesc0 *newfdp;
1759 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1760 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1762 FILEDESC_XLOCK(fdp);
1763 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1764 if (newfdp->fd_fd.fd_cdir)
1765 VREF(newfdp->fd_fd.fd_cdir);
1766 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1767 if (newfdp->fd_fd.fd_rdir)
1768 VREF(newfdp->fd_fd.fd_rdir);
1769 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1770 if (newfdp->fd_fd.fd_jdir)
1771 VREF(newfdp->fd_fd.fd_jdir);
1772 FILEDESC_XUNLOCK(fdp);
1775 /* Create the file descriptor table. */
1776 newfdp->fd_fd.fd_refcnt = 1;
1777 newfdp->fd_fd.fd_holdcnt = 1;
1778 newfdp->fd_fd.fd_cmask = CMASK;
1779 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1780 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1781 newfdp->fd_fd.fd_nfiles = NDFILE;
1782 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1783 newfdp->fd_fd.fd_lastfile = -1;
1784 return (&newfdp->fd_fd);
1787 static struct filedesc *
1788 fdhold(struct proc *p)
1790 struct filedesc *fdp;
1792 mtx_lock(&fdesc_mtx);
1796 mtx_unlock(&fdesc_mtx);
1801 fddrop(struct filedesc *fdp)
1803 struct filedesc0 *fdp0;
1804 struct freetable *ft;
1807 mtx_lock(&fdesc_mtx);
1808 i = --fdp->fd_holdcnt;
1809 mtx_unlock(&fdesc_mtx);
1813 FILEDESC_LOCK_DESTROY(fdp);
1814 fdp0 = (struct filedesc0 *)fdp;
1815 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1816 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1817 free(ft->ft_table, M_FILEDESC);
1819 free(fdp, M_FILEDESC);
1823 * Share a filedesc structure.
1826 fdshare(struct filedesc *fdp)
1829 FILEDESC_XLOCK(fdp);
1831 FILEDESC_XUNLOCK(fdp);
1836 * Unshare a filedesc structure, if necessary by making a copy
1839 fdunshare(struct proc *p, struct thread *td)
1842 FILEDESC_XLOCK(p->p_fd);
1843 if (p->p_fd->fd_refcnt > 1) {
1844 struct filedesc *tmp;
1846 FILEDESC_XUNLOCK(p->p_fd);
1847 tmp = fdcopy(p->p_fd);
1851 FILEDESC_XUNLOCK(p->p_fd);
1855 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1856 * this is to ease callers, not catch errors.
1859 fdcopy(struct filedesc *fdp)
1861 struct filedesc *newfdp;
1864 /* Certain daemons might not have file descriptors. */
1868 newfdp = fdinit(fdp);
1869 FILEDESC_SLOCK(fdp);
1870 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1871 FILEDESC_SUNLOCK(fdp);
1872 FILEDESC_XLOCK(newfdp);
1873 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1874 FILEDESC_XUNLOCK(newfdp);
1875 FILEDESC_SLOCK(fdp);
1877 /* copy all passable descriptors (i.e. not kqueue) */
1878 newfdp->fd_freefile = -1;
1879 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1880 if (fdisused(fdp, i) &&
1881 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1882 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1883 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1884 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1885 fhold(newfdp->fd_ofiles[i]);
1886 newfdp->fd_lastfile = i;
1888 if (newfdp->fd_freefile == -1)
1889 newfdp->fd_freefile = i;
1892 newfdp->fd_cmask = fdp->fd_cmask;
1893 FILEDESC_SUNLOCK(fdp);
1894 FILEDESC_XLOCK(newfdp);
1895 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1896 if (newfdp->fd_ofiles[i] != NULL)
1898 if (newfdp->fd_freefile == -1)
1899 newfdp->fd_freefile = i;
1900 FILEDESC_XUNLOCK(newfdp);
1905 * Release a filedesc structure.
1908 fdfree(struct thread *td)
1910 struct filedesc *fdp;
1913 struct filedesc_to_leader *fdtol;
1915 struct vnode *cdir, *jdir, *rdir, *vp;
1918 /* Certain daemons might not have file descriptors. */
1919 fdp = td->td_proc->p_fd;
1924 PROC_LOCK(td->td_proc);
1925 racct_set(td->td_proc, RACCT_NOFILE, 0);
1926 PROC_UNLOCK(td->td_proc);
1929 /* Check for special need to clear POSIX style locks */
1930 fdtol = td->td_proc->p_fdtol;
1931 if (fdtol != NULL) {
1932 FILEDESC_XLOCK(fdp);
1933 KASSERT(fdtol->fdl_refcount > 0,
1934 ("filedesc_to_refcount botch: fdl_refcount=%d",
1935 fdtol->fdl_refcount));
1936 if (fdtol->fdl_refcount == 1 &&
1937 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1938 for (i = 0, fpp = fdp->fd_ofiles;
1939 i <= fdp->fd_lastfile;
1942 (*fpp)->f_type != DTYPE_VNODE)
1946 FILEDESC_XUNLOCK(fdp);
1947 lf.l_whence = SEEK_SET;
1950 lf.l_type = F_UNLCK;
1952 locked = VFS_LOCK_GIANT(vp->v_mount);
1953 (void) VOP_ADVLOCK(vp,
1954 (caddr_t)td->td_proc->
1959 VFS_UNLOCK_GIANT(locked);
1960 FILEDESC_XLOCK(fdp);
1962 fpp = fdp->fd_ofiles + i;
1966 if (fdtol->fdl_refcount == 1) {
1967 if (fdp->fd_holdleaderscount > 0 &&
1968 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1970 * close() or do_dup() has cleared a reference
1971 * in a shared file descriptor table.
1973 fdp->fd_holdleaderswakeup = 1;
1974 sx_sleep(&fdp->fd_holdleaderscount,
1975 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1978 if (fdtol->fdl_holdcount > 0) {
1980 * Ensure that fdtol->fdl_leader remains
1981 * valid in closef().
1983 fdtol->fdl_wakeup = 1;
1984 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1989 fdtol->fdl_refcount--;
1990 if (fdtol->fdl_refcount == 0 &&
1991 fdtol->fdl_holdcount == 0) {
1992 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1993 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1996 td->td_proc->p_fdtol = NULL;
1997 FILEDESC_XUNLOCK(fdp);
1999 free(fdtol, M_FILEDESC_TO_LEADER);
2001 FILEDESC_XLOCK(fdp);
2002 i = --fdp->fd_refcnt;
2003 FILEDESC_XUNLOCK(fdp);
2007 fpp = fdp->fd_ofiles;
2008 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
2010 FILEDESC_XLOCK(fdp);
2013 FILEDESC_XUNLOCK(fdp);
2014 (void) closef(fp, td);
2017 FILEDESC_XLOCK(fdp);
2019 /* XXX This should happen earlier. */
2020 mtx_lock(&fdesc_mtx);
2021 td->td_proc->p_fd = NULL;
2022 mtx_unlock(&fdesc_mtx);
2024 if (fdp->fd_nfiles > NDFILE)
2025 free(fdp->fd_ofiles, M_FILEDESC);
2026 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2027 free(fdp->fd_map, M_FILEDESC);
2031 cdir = fdp->fd_cdir;
2032 fdp->fd_cdir = NULL;
2033 rdir = fdp->fd_rdir;
2034 fdp->fd_rdir = NULL;
2035 jdir = fdp->fd_jdir;
2036 fdp->fd_jdir = NULL;
2037 FILEDESC_XUNLOCK(fdp);
2040 locked = VFS_LOCK_GIANT(cdir->v_mount);
2042 VFS_UNLOCK_GIANT(locked);
2045 locked = VFS_LOCK_GIANT(rdir->v_mount);
2047 VFS_UNLOCK_GIANT(locked);
2050 locked = VFS_LOCK_GIANT(jdir->v_mount);
2052 VFS_UNLOCK_GIANT(locked);
2059 * For setugid programs, we don't want to people to use that setugidness
2060 * to generate error messages which write to a file which otherwise would
2061 * otherwise be off-limits to the process. We check for filesystems where
2062 * the vnode can change out from under us after execve (like [lin]procfs).
2064 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2065 * sufficient. We also don't check for setugidness since we know we are.
2068 is_unsafe(struct file *fp)
2070 if (fp->f_type == DTYPE_VNODE) {
2071 struct vnode *vp = fp->f_vnode;
2073 if ((vp->v_vflag & VV_PROCDEP) != 0)
2080 * Make this setguid thing safe, if at all possible.
2083 setugidsafety(struct thread *td)
2085 struct filedesc *fdp;
2088 /* Certain daemons might not have file descriptors. */
2089 fdp = td->td_proc->p_fd;
2094 * Note: fdp->fd_ofiles may be reallocated out from under us while
2095 * we are blocked in a close. Be careful!
2097 FILEDESC_XLOCK(fdp);
2098 for (i = 0; i <= fdp->fd_lastfile; i++) {
2101 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2104 knote_fdclose(td, i);
2106 * NULL-out descriptor prior to close to avoid
2107 * a race while close blocks.
2109 fp = fdp->fd_ofiles[i];
2110 fdp->fd_ofiles[i] = NULL;
2111 fdp->fd_ofileflags[i] = 0;
2113 FILEDESC_XUNLOCK(fdp);
2114 (void) closef(fp, td);
2115 FILEDESC_XLOCK(fdp);
2118 FILEDESC_XUNLOCK(fdp);
2122 * If a specific file object occupies a specific file descriptor, close the
2123 * file descriptor entry and drop a reference on the file object. This is a
2124 * convenience function to handle a subsequent error in a function that calls
2125 * falloc() that handles the race that another thread might have closed the
2126 * file descriptor out from under the thread creating the file object.
2129 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2132 FILEDESC_XLOCK(fdp);
2133 if (fdp->fd_ofiles[idx] == fp) {
2134 fdp->fd_ofiles[idx] = NULL;
2136 FILEDESC_XUNLOCK(fdp);
2139 FILEDESC_XUNLOCK(fdp);
2143 * Close any files on exec?
2146 fdcloseexec(struct thread *td)
2148 struct filedesc *fdp;
2151 /* Certain daemons might not have file descriptors. */
2152 fdp = td->td_proc->p_fd;
2156 FILEDESC_XLOCK(fdp);
2159 * We cannot cache fd_ofiles or fd_ofileflags since operations
2160 * may block and rip them out from under us.
2162 for (i = 0; i <= fdp->fd_lastfile; i++) {
2163 if (fdp->fd_ofiles[i] != NULL &&
2164 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2165 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2168 knote_fdclose(td, i);
2170 * NULL-out descriptor prior to close to avoid
2171 * a race while close blocks.
2173 fp = fdp->fd_ofiles[i];
2174 fdp->fd_ofiles[i] = NULL;
2175 fdp->fd_ofileflags[i] = 0;
2177 if (fp->f_type == DTYPE_MQUEUE)
2178 mq_fdclose(td, i, fp);
2179 FILEDESC_XUNLOCK(fdp);
2180 (void) closef(fp, td);
2181 FILEDESC_XLOCK(fdp);
2184 FILEDESC_XUNLOCK(fdp);
2188 * It is unsafe for set[ug]id processes to be started with file
2189 * descriptors 0..2 closed, as these descriptors are given implicit
2190 * significance in the Standard C library. fdcheckstd() will create a
2191 * descriptor referencing /dev/null for each of stdin, stdout, and
2192 * stderr that is not already open.
2195 fdcheckstd(struct thread *td)
2197 struct filedesc *fdp;
2198 register_t retval, save;
2199 int i, error, devnull;
2201 fdp = td->td_proc->p_fd;
2204 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2207 for (i = 0; i < 3; i++) {
2208 if (fdp->fd_ofiles[i] != NULL)
2211 save = td->td_retval[0];
2212 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2214 devnull = td->td_retval[0];
2215 td->td_retval[0] = save;
2218 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2220 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2229 * Internal form of close. Decrement reference count on file structure.
2230 * Note: td may be NULL when closing a file that was being passed in a
2233 * XXXRW: Giant is not required for the caller, but often will be held; this
2234 * makes it moderately likely the Giant will be recursed in the VFS case.
2237 closef(struct file *fp, struct thread *td)
2241 struct filedesc_to_leader *fdtol;
2242 struct filedesc *fdp;
2243 struct file *fp_object;
2246 * POSIX record locking dictates that any close releases ALL
2247 * locks owned by this process. This is handled by setting
2248 * a flag in the unlock to free ONLY locks obeying POSIX
2249 * semantics, and not to free BSD-style file locks.
2250 * If the descriptor was in a message, POSIX-style locks
2251 * aren't passed with the descriptor, and the thread pointer
2252 * will be NULL. Callers should be careful only to pass a
2253 * NULL thread pointer when there really is no owning
2254 * context that might have locks, or the locks will be
2257 * If this is a capability, we do lock processing under the underlying
2258 * node, not the capability itself.
2260 (void)cap_funwrap(fp, 0, &fp_object);
2261 if ((fp_object->f_type == DTYPE_VNODE) && (td != NULL)) {
2264 vp = fp_object->f_vnode;
2265 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2266 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2267 lf.l_whence = SEEK_SET;
2270 lf.l_type = F_UNLCK;
2271 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2272 F_UNLCK, &lf, F_POSIX);
2274 fdtol = td->td_proc->p_fdtol;
2275 if (fdtol != NULL) {
2277 * Handle special case where file descriptor table is
2278 * shared between multiple process leaders.
2280 fdp = td->td_proc->p_fd;
2281 FILEDESC_XLOCK(fdp);
2282 for (fdtol = fdtol->fdl_next;
2283 fdtol != td->td_proc->p_fdtol;
2284 fdtol = fdtol->fdl_next) {
2285 if ((fdtol->fdl_leader->p_flag &
2288 fdtol->fdl_holdcount++;
2289 FILEDESC_XUNLOCK(fdp);
2290 lf.l_whence = SEEK_SET;
2293 lf.l_type = F_UNLCK;
2294 vp = fp_object->f_vnode;
2295 (void) VOP_ADVLOCK(vp,
2296 (caddr_t)fdtol->fdl_leader,
2297 F_UNLCK, &lf, F_POSIX);
2298 FILEDESC_XLOCK(fdp);
2299 fdtol->fdl_holdcount--;
2300 if (fdtol->fdl_holdcount == 0 &&
2301 fdtol->fdl_wakeup != 0) {
2302 fdtol->fdl_wakeup = 0;
2306 FILEDESC_XUNLOCK(fdp);
2308 VFS_UNLOCK_GIANT(vfslocked);
2310 return (fdrop(fp, td));
2314 * Initialize the file pointer with the specified properties.
2316 * The ops are set with release semantics to be certain that the flags, type,
2317 * and data are visible when ops is. This is to prevent ops methods from being
2318 * called with bad data.
2321 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2326 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2330 fget_unlocked(struct filedesc *fdp, int fd)
2335 if (fd < 0 || fd >= fdp->fd_nfiles)
2338 * Fetch the descriptor locklessly. We avoid fdrop() races by
2339 * never raising a refcount above 0. To accomplish this we have
2340 * to use a cmpset loop rather than an atomic_add. The descriptor
2341 * must be re-verified once we acquire a reference to be certain
2342 * that the identity is still correct and we did not lose a race
2343 * due to preemption.
2346 fp = fdp->fd_ofiles[fd];
2349 count = fp->f_count;
2353 * Use an acquire barrier to prevent caching of fd_ofiles
2354 * so it is refreshed for verification.
2356 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2358 if (fp == fdp->fd_ofiles[fd])
2360 fdrop(fp, curthread);
2367 * Extract the file pointer associated with the specified descriptor for the
2368 * current user process.
2370 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2373 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2374 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2375 * Otherwise, if the file is a capability, its rights will be checked against
2376 * the capability rights mask, and if successful, the object will be unwrapped.
2378 * If an error occured the non-zero error is returned and *fpp is set to
2379 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2380 * responsible for fdrop().
2382 #define FGET_GETCAP 0x00000001
2384 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2385 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2388 struct filedesc *fdp;
2391 struct file *fp_fromcap;
2396 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2398 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2400 if (fp->f_ops == &badfileops) {
2407 * If this is a capability, what rights does it have?
2409 if (haverightsp != NULL) {
2410 if (fp->f_type == DTYPE_CAPABILITY)
2411 *haverightsp = cap_rights(fp);
2413 *haverightsp = CAP_MASK_VALID;
2417 * If a capability has been requested, return the capability directly.
2418 * Otherwise, check capability rights, extract the underlying object,
2419 * and check its access flags.
2421 if (fget_flags & FGET_GETCAP) {
2422 if (fp->f_type != DTYPE_CAPABILITY) {
2427 if (maxprotp == NULL)
2428 error = cap_funwrap(fp, needrights, &fp_fromcap);
2430 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2438 * If we've unwrapped a file, drop the original capability
2439 * and hold the new descriptor. fp after this point refers to
2440 * the actual (unwrapped) object, not the capability.
2442 if (fp != fp_fromcap) {
2448 #else /* !CAPABILITIES */
2449 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2450 ("%s: saw capability", __func__));
2451 if (maxprotp != NULL)
2452 *maxprotp = VM_PROT_ALL;
2453 #endif /* CAPABILITIES */
2456 * FREAD and FWRITE failure return EBADF as per POSIX.
2462 if ((fp->f_flag & flags) == 0)
2466 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2467 ((fp->f_flag & FWRITE) != 0))
2473 KASSERT(0, ("wrong flags"));
2486 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2489 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2493 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2497 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2501 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2504 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2508 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2511 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2515 * Unlike the other fget() calls, which accept and check capability rights
2516 * but never return capabilities, fgetcap() returns the capability but doesn't
2517 * check capability rights.
2520 fgetcap(struct thread *td, int fd, struct file **fpp)
2523 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2528 * Like fget() but loads the underlying vnode, or returns an error if the
2529 * descriptor does not represent a vnode. Note that pipes use vnodes but
2530 * never have VM objects. The returned vnode will be vref()'d.
2532 * XXX: what about the unused flags ?
2535 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2536 cap_rights_t *haverightsp, struct vnode **vpp)
2542 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2545 if (fp->f_vnode == NULL) {
2557 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2560 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2564 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2567 return (_fgetvp(td, fd, 0, need, have, vpp));
2571 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2574 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2578 fgetvp_exec(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2581 return (_fgetvp(td, fd, FEXEC, rights, NULL, vpp));
2586 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2590 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2595 * Like fget() but loads the underlying socket, or returns an error if the
2596 * descriptor does not represent a socket.
2598 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2601 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2602 * on their file descriptor reference to prevent the socket from being free'd
2606 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2615 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2617 if (fp->f_type != DTYPE_SOCKET) {
2622 *fflagp = fp->f_flag;
2633 * Drop the reference count on the socket and XXX release the SX lock in the
2634 * future. The last reference closes the socket.
2636 * Note: fputsock() is deprecated, see comment for fgetsock().
2639 fputsock(struct socket *so)
2644 CURVNET_SET(so->so_vnet);
2650 * Handle the last reference to a file being closed.
2652 * No special capability handling here, as the capability's fo_close will run
2653 * instead of the object here, and perform any necessary drop on the object.
2656 _fdrop(struct file *fp, struct thread *td)
2661 if (fp->f_count != 0)
2662 panic("fdrop: count %d", fp->f_count);
2663 if (fp->f_ops != &badfileops)
2664 error = fo_close(fp, td);
2665 atomic_subtract_int(&openfiles, 1);
2667 free(fp->f_advice, M_FADVISE);
2668 uma_zfree(file_zone, fp);
2674 * Apply an advisory lock on a file descriptor.
2676 * Just attempt to get a record lock of the requested type on the entire file
2677 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2679 #ifndef _SYS_SYSPROTO_H_
2687 sys_flock(struct thread *td, struct flock_args *uap)
2695 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2697 if (fp->f_type != DTYPE_VNODE) {
2699 return (EOPNOTSUPP);
2703 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2704 lf.l_whence = SEEK_SET;
2707 if (uap->how & LOCK_UN) {
2708 lf.l_type = F_UNLCK;
2709 atomic_clear_int(&fp->f_flag, FHASLOCK);
2710 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2713 if (uap->how & LOCK_EX)
2714 lf.l_type = F_WRLCK;
2715 else if (uap->how & LOCK_SH)
2716 lf.l_type = F_RDLCK;
2721 atomic_set_int(&fp->f_flag, FHASLOCK);
2722 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2723 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2726 VFS_UNLOCK_GIANT(vfslocked);
2730 * Duplicate the specified descriptor to a free descriptor.
2733 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2739 * If the to-be-dup'd fd number is greater than the allowed number
2740 * of file descriptors, or the fd to be dup'd has already been
2741 * closed, then reject.
2743 FILEDESC_XLOCK(fdp);
2744 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2745 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2746 FILEDESC_XUNLOCK(fdp);
2751 * There are two cases of interest here.
2753 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2755 * For ENXIO steal away the file structure from (dfd) and store it in
2756 * (indx). (dfd) is effectively closed by this operation.
2758 * Any other error code is just returned.
2763 * Check that the mode the file is being opened for is a
2764 * subset of the mode of the existing descriptor.
2766 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2767 FILEDESC_XUNLOCK(fdp);
2770 fp = fdp->fd_ofiles[indx];
2771 fdp->fd_ofiles[indx] = wfp;
2772 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2776 FILEDESC_XUNLOCK(fdp);
2779 * We now own the reference to fp that the ofiles[]
2780 * array used to own. Release it.
2787 * Steal away the file pointer from dfd and stuff it into indx.
2789 fp = fdp->fd_ofiles[indx];
2790 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2791 fdp->fd_ofiles[dfd] = NULL;
2792 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2793 fdp->fd_ofileflags[dfd] = 0;
2797 FILEDESC_XUNLOCK(fdp);
2800 * We now own the reference to fp that the ofiles[] array
2801 * used to own. Release it.
2808 FILEDESC_XUNLOCK(fdp);
2815 * Scan all active processes and prisons to see if any of them have a current
2816 * or root directory of `olddp'. If so, replace them with the new mount point.
2819 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2821 struct filedesc *fdp;
2826 if (vrefcnt(olddp) == 1)
2829 sx_slock(&allproc_lock);
2830 FOREACH_PROC_IN_SYSTEM(p) {
2834 FILEDESC_XLOCK(fdp);
2835 if (fdp->fd_cdir == olddp) {
2837 fdp->fd_cdir = newdp;
2840 if (fdp->fd_rdir == olddp) {
2842 fdp->fd_rdir = newdp;
2845 if (fdp->fd_jdir == olddp) {
2847 fdp->fd_jdir = newdp;
2850 FILEDESC_XUNLOCK(fdp);
2853 sx_sunlock(&allproc_lock);
2854 if (rootvnode == olddp) {
2859 mtx_lock(&prison0.pr_mtx);
2860 if (prison0.pr_root == olddp) {
2862 prison0.pr_root = newdp;
2865 mtx_unlock(&prison0.pr_mtx);
2866 sx_slock(&allprison_lock);
2867 TAILQ_FOREACH(pr, &allprison, pr_list) {
2868 mtx_lock(&pr->pr_mtx);
2869 if (pr->pr_root == olddp) {
2871 pr->pr_root = newdp;
2874 mtx_unlock(&pr->pr_mtx);
2876 sx_sunlock(&allprison_lock);
2881 struct filedesc_to_leader *
2882 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2884 struct filedesc_to_leader *fdtol;
2886 fdtol = malloc(sizeof(struct filedesc_to_leader),
2887 M_FILEDESC_TO_LEADER,
2889 fdtol->fdl_refcount = 1;
2890 fdtol->fdl_holdcount = 0;
2891 fdtol->fdl_wakeup = 0;
2892 fdtol->fdl_leader = leader;
2894 FILEDESC_XLOCK(fdp);
2895 fdtol->fdl_next = old->fdl_next;
2896 fdtol->fdl_prev = old;
2897 old->fdl_next = fdtol;
2898 fdtol->fdl_next->fdl_prev = fdtol;
2899 FILEDESC_XUNLOCK(fdp);
2901 fdtol->fdl_next = fdtol;
2902 fdtol->fdl_prev = fdtol;
2908 * Get file structures globally.
2911 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2914 struct filedesc *fdp;
2919 error = sysctl_wire_old_buffer(req, 0);
2922 if (req->oldptr == NULL) {
2924 sx_slock(&allproc_lock);
2925 FOREACH_PROC_IN_SYSTEM(p) {
2926 if (p->p_state == PRS_NEW)
2931 /* overestimates sparse tables. */
2932 if (fdp->fd_lastfile > 0)
2933 n += fdp->fd_lastfile;
2936 sx_sunlock(&allproc_lock);
2937 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2940 bzero(&xf, sizeof(xf));
2941 xf.xf_size = sizeof(xf);
2942 sx_slock(&allproc_lock);
2943 FOREACH_PROC_IN_SYSTEM(p) {
2945 if (p->p_state == PRS_NEW) {
2949 if (p_cansee(req->td, p) != 0) {
2953 xf.xf_pid = p->p_pid;
2954 xf.xf_uid = p->p_ucred->cr_uid;
2959 FILEDESC_SLOCK(fdp);
2960 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2961 if ((fp = fdp->fd_ofiles[n]) == NULL)
2965 xf.xf_data = fp->f_data;
2966 xf.xf_vnode = fp->f_vnode;
2967 xf.xf_type = fp->f_type;
2968 xf.xf_count = fp->f_count;
2970 xf.xf_offset = foffset_get(fp);
2971 xf.xf_flag = fp->f_flag;
2972 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2976 FILEDESC_SUNLOCK(fdp);
2981 sx_sunlock(&allproc_lock);
2985 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2986 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2988 #ifdef KINFO_OFILE_SIZE
2989 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2992 #ifdef COMPAT_FREEBSD7
2994 export_vnode_for_osysctl(struct vnode *vp, int type,
2995 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2998 char *fullpath, *freepath;
3001 bzero(kif, sizeof(*kif));
3002 kif->kf_structsize = sizeof(*kif);
3006 kif->kf_type = KF_TYPE_VNODE;
3007 /* This function only handles directories. */
3008 if (vp->v_type != VDIR) {
3012 kif->kf_vnode_type = KF_VTYPE_VDIR;
3015 * This is not a true file descriptor, so we set a bogus refcount
3016 * and offset to indicate these fields should be ignored.
3018 kif->kf_ref_count = -1;
3019 kif->kf_offset = -1;
3023 FILEDESC_SUNLOCK(fdp);
3024 vn_fullpath(curthread, vp, &fullpath, &freepath);
3025 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3027 VFS_UNLOCK_GIANT(vfslocked);
3028 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3029 if (freepath != NULL)
3030 free(freepath, M_TEMP);
3031 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3032 FILEDESC_SLOCK(fdp);
3037 * Get per-process file descriptors for use by procstat(1), et al.
3040 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3042 char *fullpath, *freepath;
3043 struct kinfo_ofile *kif;
3044 struct filedesc *fdp;
3045 int error, i, *name;
3046 struct shmfd *shmfd;
3056 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3063 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3064 FILEDESC_SLOCK(fdp);
3065 if (fdp->fd_cdir != NULL)
3066 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3068 if (fdp->fd_rdir != NULL)
3069 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3071 if (fdp->fd_jdir != NULL)
3072 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3074 for (i = 0; i < fdp->fd_nfiles; i++) {
3075 if ((fp = fdp->fd_ofiles[i]) == NULL)
3077 bzero(kif, sizeof(*kif));
3078 kif->kf_structsize = sizeof(*kif);
3088 * When reporting a capability, most fields will be from the
3089 * underlying object, but do mark as a capability. With
3090 * ofiledesc, we don't have a field to export the cap_rights_t,
3091 * but we do with the new filedesc.
3093 if (fp->f_type == DTYPE_CAPABILITY) {
3094 kif->kf_flags |= KF_FLAG_CAPABILITY;
3095 (void)cap_funwrap(fp, 0, &fp);
3098 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3099 ("sysctl_kern_proc_ofiledesc: saw capability"));
3101 switch (fp->f_type) {
3103 kif->kf_type = KF_TYPE_VNODE;
3108 kif->kf_type = KF_TYPE_SOCKET;
3113 kif->kf_type = KF_TYPE_PIPE;
3117 kif->kf_type = KF_TYPE_FIFO;
3122 kif->kf_type = KF_TYPE_KQUEUE;
3126 kif->kf_type = KF_TYPE_CRYPTO;
3130 kif->kf_type = KF_TYPE_MQUEUE;
3134 kif->kf_type = KF_TYPE_SHM;
3139 kif->kf_type = KF_TYPE_SEM;
3144 kif->kf_type = KF_TYPE_PTS;
3149 case DTYPE_PROCDESC:
3150 kif->kf_type = KF_TYPE_PROCDESC;
3155 kif->kf_type = KF_TYPE_UNKNOWN;
3158 kif->kf_ref_count = fp->f_count;
3159 if (fp->f_flag & FREAD)
3160 kif->kf_flags |= KF_FLAG_READ;
3161 if (fp->f_flag & FWRITE)
3162 kif->kf_flags |= KF_FLAG_WRITE;
3163 if (fp->f_flag & FAPPEND)
3164 kif->kf_flags |= KF_FLAG_APPEND;
3165 if (fp->f_flag & FASYNC)
3166 kif->kf_flags |= KF_FLAG_ASYNC;
3167 if (fp->f_flag & FFSYNC)
3168 kif->kf_flags |= KF_FLAG_FSYNC;
3169 if (fp->f_flag & FNONBLOCK)
3170 kif->kf_flags |= KF_FLAG_NONBLOCK;
3171 if (fp->f_flag & O_DIRECT)
3172 kif->kf_flags |= KF_FLAG_DIRECT;
3173 if (fp->f_flag & FHASLOCK)
3174 kif->kf_flags |= KF_FLAG_HASLOCK;
3175 kif->kf_offset = foffset_get(fp);
3178 switch (vp->v_type) {
3180 kif->kf_vnode_type = KF_VTYPE_VNON;
3183 kif->kf_vnode_type = KF_VTYPE_VREG;
3186 kif->kf_vnode_type = KF_VTYPE_VDIR;
3189 kif->kf_vnode_type = KF_VTYPE_VBLK;
3192 kif->kf_vnode_type = KF_VTYPE_VCHR;
3195 kif->kf_vnode_type = KF_VTYPE_VLNK;
3198 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3201 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3204 kif->kf_vnode_type = KF_VTYPE_VBAD;
3207 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3211 * It is OK to drop the filedesc lock here as we will
3212 * re-validate and re-evaluate its properties when
3213 * the loop continues.
3217 FILEDESC_SUNLOCK(fdp);
3218 vn_fullpath(curthread, vp, &fullpath, &freepath);
3219 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3221 VFS_UNLOCK_GIANT(vfslocked);
3222 strlcpy(kif->kf_path, fullpath,
3223 sizeof(kif->kf_path));
3224 if (freepath != NULL)
3225 free(freepath, M_TEMP);
3226 FILEDESC_SLOCK(fdp);
3229 struct sockaddr *sa;
3231 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3232 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3233 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3236 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3237 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3238 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3241 kif->kf_sock_domain =
3242 so->so_proto->pr_domain->dom_family;
3243 kif->kf_sock_type = so->so_type;
3244 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3247 strlcpy(kif->kf_path, tty_devname(tp),
3248 sizeof(kif->kf_path));
3251 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3252 if (ks != NULL && ksem_info != NULL)
3253 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3254 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3258 FILEDESC_SUNLOCK(fdp);
3264 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3265 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3266 #endif /* COMPAT_FREEBSD7 */
3268 #ifdef KINFO_FILE_SIZE
3269 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3272 struct export_fd_buf {
3273 struct filedesc *fdp;
3276 struct kinfo_file kif;
3280 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3281 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3282 struct export_fd_buf *efbuf)
3287 } fflags_table[] = {
3288 { FAPPEND, KF_FLAG_APPEND },
3289 { FASYNC, KF_FLAG_ASYNC },
3290 { FFSYNC, KF_FLAG_FSYNC },
3291 { FHASLOCK, KF_FLAG_HASLOCK },
3292 { FNONBLOCK, KF_FLAG_NONBLOCK },
3293 { FREAD, KF_FLAG_READ },
3294 { FWRITE, KF_FLAG_WRITE },
3295 { O_CREAT, KF_FLAG_CREAT },
3296 { O_DIRECT, KF_FLAG_DIRECT },
3297 { O_EXCL, KF_FLAG_EXCL },
3298 { O_EXEC, KF_FLAG_EXEC },
3299 { O_EXLOCK, KF_FLAG_EXLOCK },
3300 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3301 { O_SHLOCK, KF_FLAG_SHLOCK },
3302 { O_TRUNC, KF_FLAG_TRUNC }
3304 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3305 struct kinfo_file *kif;
3307 int error, locked, vfslocked;
3310 if (efbuf->remainder == 0)
3313 bzero(kif, sizeof(*kif));
3314 locked = efbuf->fdp != NULL;
3319 FILEDESC_SUNLOCK(efbuf->fdp);
3322 vp = (struct vnode *)data;
3323 error = fill_vnode_info(vp, kif);
3324 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3326 VFS_UNLOCK_GIANT(vfslocked);
3328 case KF_TYPE_SOCKET:
3329 error = fill_socket_info((struct socket *)data, kif);
3332 error = fill_pipe_info((struct pipe *)data, kif);
3335 error = fill_pts_info((struct tty *)data, kif);
3337 case KF_TYPE_PROCDESC:
3338 error = fill_procdesc_info((struct procdesc *)data, kif);
3341 error = fill_sem_info((struct file *)data, kif);
3344 error = fill_shm_info((struct file *)data, kif);
3350 kif->kf_status |= KF_ATTR_VALID;
3353 * Translate file access flags.
3355 for (i = 0; i < NFFLAGS; i++)
3356 if (fflags & fflags_table[i].fflag)
3357 kif->kf_flags |= fflags_table[i].kf_fflag;
3359 kif->kf_flags |= KF_FLAG_CAPABILITY;
3361 kif->kf_cap_rights = fd_cap_rights;
3363 kif->kf_type = type;
3364 kif->kf_ref_count = refcnt;
3365 kif->kf_offset = offset;
3366 /* Pack record size down */
3367 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3368 strlen(kif->kf_path) + 1;
3369 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3370 if (efbuf->remainder != -1) {
3371 if (efbuf->remainder < kif->kf_structsize) {
3372 /* Terminate export. */
3373 efbuf->remainder = 0;
3374 if (efbuf->fdp != NULL && !locked)
3375 FILEDESC_SLOCK(efbuf->fdp);
3378 efbuf->remainder -= kif->kf_structsize;
3381 FILEDESC_SUNLOCK(efbuf->fdp);
3382 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3383 if (efbuf->fdp != NULL)
3384 FILEDESC_SLOCK(efbuf->fdp);
3389 * Store a process file descriptor information to sbuf.
3391 * Takes a locked proc as argument, and returns with the proc unlocked.
3394 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3397 struct filedesc *fdp;
3398 struct export_fd_buf *efbuf;
3399 struct vnode *cttyvp, *textvp, *tracevp;
3403 int fd_is_cap, type, refcnt, fflags;
3404 cap_rights_t fd_cap_rights;
3406 PROC_LOCK_ASSERT(p, MA_OWNED);
3409 tracevp = p->p_tracevp;
3410 if (tracevp != NULL)
3413 textvp = p->p_textvp;
3416 /* Controlling tty. */
3418 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3419 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3425 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3428 efbuf->remainder = maxlen;
3429 if (tracevp != NULL)
3430 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3431 FREAD | FWRITE, -1, -1, 0, 0, efbuf);
3433 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3434 FREAD, -1, -1, 0, 0, efbuf);
3436 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3437 FREAD | FWRITE, -1, -1, 0, 0, efbuf);
3442 FILEDESC_SLOCK(fdp);
3443 /* working directory */
3444 if (fdp->fd_cdir != NULL) {
3446 data = fdp->fd_cdir;
3447 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3448 FREAD, -1, -1, 0, 0, efbuf);
3450 /* root directory */
3451 if (fdp->fd_rdir != NULL) {
3453 data = fdp->fd_rdir;
3454 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3455 FREAD, -1, -1, 0, 0, efbuf);
3457 /* jail directory */
3458 if (fdp->fd_jdir != NULL) {
3460 data = fdp->fd_jdir;
3461 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3462 FREAD, -1, -1, 0, 0, efbuf);
3464 for (i = 0; i < fdp->fd_nfiles; i++) {
3465 if ((fp = fdp->fd_ofiles[i]) == NULL)
3473 * When reporting a capability, most fields will be from the
3474 * underlying object, but do mark as a capability and export
3475 * the capability rights mask.
3477 if (fp->f_type == DTYPE_CAPABILITY) {
3479 fd_cap_rights = cap_rights(fp);
3480 (void)cap_funwrap(fp, 0, &fp);
3482 #else /* !CAPABILITIES */
3483 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3484 ("sysctl_kern_proc_filedesc: saw capability"));
3486 switch (fp->f_type) {
3488 type = KF_TYPE_VNODE;
3494 type = KF_TYPE_SOCKET;
3499 type = KF_TYPE_PIPE;
3504 type = KF_TYPE_FIFO;
3510 type = KF_TYPE_KQUEUE;
3514 type = KF_TYPE_CRYPTO;
3518 type = KF_TYPE_MQUEUE;
3537 case DTYPE_PROCDESC:
3538 type = KF_TYPE_PROCDESC;
3544 type = KF_TYPE_UNKNOWN;
3547 refcnt = fp->f_count;
3548 fflags = fp->f_flag;
3549 offset = foffset_get(fp);
3552 * Create sysctl entry.
3553 * It is OK to drop the filedesc lock here as we will
3554 * re-validate and re-evaluate its properties when
3555 * the loop continues.
3557 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3558 offset, fd_is_cap, fd_cap_rights, efbuf);
3562 FILEDESC_SUNLOCK(fdp);
3565 free(efbuf, M_TEMP);
3569 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3572 * Get per-process file descriptors for use by procstat(1), et al.
3575 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3580 int error, error2, *name;
3584 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3585 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3590 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3591 error = kern_proc_filedesc_out(p, &sb, maxlen);
3592 error2 = sbuf_finish(&sb);
3594 return (error != 0 ? error : error2);
3598 vntype_to_kinfo(int vtype)
3603 } vtypes_table[] = {
3604 { VBAD, KF_VTYPE_VBAD },
3605 { VBLK, KF_VTYPE_VBLK },
3606 { VCHR, KF_VTYPE_VCHR },
3607 { VDIR, KF_VTYPE_VDIR },
3608 { VFIFO, KF_VTYPE_VFIFO },
3609 { VLNK, KF_VTYPE_VLNK },
3610 { VNON, KF_VTYPE_VNON },
3611 { VREG, KF_VTYPE_VREG },
3612 { VSOCK, KF_VTYPE_VSOCK }
3614 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3618 * Perform vtype translation.
3620 for (i = 0; i < NVTYPES; i++)
3621 if (vtypes_table[i].vtype == vtype)
3624 return (vtypes_table[i].kf_vtype);
3626 return (KF_VTYPE_UNKNOWN);
3630 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3633 char *fullpath, *freepath;
3634 int error, vfslocked;
3638 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3641 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3643 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3645 if (freepath != NULL)
3646 free(freepath, M_TEMP);
3649 * Retrieve vnode attributes.
3651 va.va_fsid = VNOVAL;
3653 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3654 vn_lock(vp, LK_SHARED | LK_RETRY);
3655 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3657 VFS_UNLOCK_GIANT(vfslocked);
3660 if (va.va_fsid != VNOVAL)
3661 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3663 kif->kf_un.kf_file.kf_file_fsid =
3664 vp->v_mount->mnt_stat.f_fsid.val[0];
3665 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3666 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3667 kif->kf_un.kf_file.kf_file_size = va.va_size;
3668 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3673 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3675 struct sockaddr *sa;
3676 struct inpcb *inpcb;
3677 struct unpcb *unpcb;
3682 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3683 kif->kf_sock_type = so->so_type;
3684 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3685 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3686 switch(kif->kf_sock_domain) {
3689 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3690 if (so->so_pcb != NULL) {
3691 inpcb = (struct inpcb *)(so->so_pcb);
3692 kif->kf_un.kf_sock.kf_sock_inpcb =
3693 (uintptr_t)inpcb->inp_ppcb;
3698 if (so->so_pcb != NULL) {
3699 unpcb = (struct unpcb *)(so->so_pcb);
3700 if (unpcb->unp_conn) {
3701 kif->kf_un.kf_sock.kf_sock_unpconn =
3702 (uintptr_t)unpcb->unp_conn;
3703 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3704 so->so_rcv.sb_state;
3705 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3706 so->so_snd.sb_state;
3711 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3712 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3713 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3716 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3717 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3718 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3721 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3722 sizeof(kif->kf_path));
3727 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3732 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3733 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3738 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3743 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3744 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3745 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3750 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3755 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3760 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3766 if (fp->f_data == NULL)
3768 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3770 if (ksem_info == NULL)
3772 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3773 &kif->kf_un.kf_sem.kf_sem_value);
3774 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3779 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3785 if (fp->f_data == NULL)
3787 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3789 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3790 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3791 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3795 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3796 sysctl_kern_proc_filedesc, "Process filedesc entries");
3800 * For the purposes of debugging, generate a human-readable string for the
3804 file_type_to_name(short type)
3834 * For the purposes of debugging, identify a process (if any, perhaps one of
3835 * many) that references the passed file in its file descriptor array. Return
3838 static struct proc *
3839 file_to_first_proc(struct file *fp)
3841 struct filedesc *fdp;
3845 FOREACH_PROC_IN_SYSTEM(p) {
3846 if (p->p_state == PRS_NEW)
3851 for (n = 0; n < fdp->fd_nfiles; n++) {
3852 if (fp == fdp->fd_ofiles[n])
3860 db_print_file(struct file *fp, int header)
3865 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3866 "File", "Type", "Data", "Flag", "GCFl", "Count",
3867 "MCount", "Vnode", "FPID", "FCmd");
3868 p = file_to_first_proc(fp);
3869 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3870 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3871 0, fp->f_count, 0, fp->f_vnode,
3872 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3875 DB_SHOW_COMMAND(file, db_show_file)
3880 db_printf("usage: show file <addr>\n");
3883 fp = (struct file *)addr;
3884 db_print_file(fp, 1);
3887 DB_SHOW_COMMAND(files, db_show_files)
3889 struct filedesc *fdp;
3896 FOREACH_PROC_IN_SYSTEM(p) {
3897 if (p->p_state == PRS_NEW)
3899 if ((fdp = p->p_fd) == NULL)
3901 for (n = 0; n < fdp->fd_nfiles; ++n) {
3902 if ((fp = fdp->fd_ofiles[n]) == NULL)
3904 db_print_file(fp, header);
3911 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3912 &maxfilesperproc, 0, "Maximum files allowed open per process");
3914 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3915 &maxfiles, 0, "Maximum number of files");
3917 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3918 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3922 filelistinit(void *dummy)
3925 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3926 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3927 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3928 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3930 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3932 /*-------------------------------------------------------------------*/
3935 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3936 int flags, struct thread *td)
3943 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3951 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3959 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3967 badfo_kqfilter(struct file *fp, struct knote *kn)
3974 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3982 badfo_close(struct file *fp, struct thread *td)
3989 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3997 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4004 struct fileops badfileops = {
4005 .fo_read = badfo_readwrite,
4006 .fo_write = badfo_readwrite,
4007 .fo_truncate = badfo_truncate,
4008 .fo_ioctl = badfo_ioctl,
4009 .fo_poll = badfo_poll,
4010 .fo_kqfilter = badfo_kqfilter,
4011 .fo_stat = badfo_stat,
4012 .fo_close = badfo_close,
4013 .fo_chmod = badfo_chmod,
4014 .fo_chown = badfo_chown,
4018 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4026 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4033 /*-------------------------------------------------------------------*/
4036 * File Descriptor pseudo-device driver (/dev/fd/).
4038 * Opening minor device N dup()s the file (if any) connected to file
4039 * descriptor N belonging to the calling process. Note that this driver
4040 * consists of only the ``open()'' routine, because all subsequent
4041 * references to this file will be direct to the other driver.
4043 * XXX: we could give this one a cloning event handler if necessary.
4048 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4052 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4053 * the file descriptor being sought for duplication. The error
4054 * return ensures that the vnode for this device will be released
4055 * by vn_open. Open will detect this special error and take the
4056 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4057 * will simply report the error.
4059 td->td_dupfd = dev2unit(dev);
4063 static struct cdevsw fildesc_cdevsw = {
4064 .d_version = D_VERSION,
4070 fildesc_drvinit(void *unused)
4074 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4075 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4076 make_dev_alias(dev, "stdin");
4077 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4078 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4079 make_dev_alias(dev, "stdout");
4080 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4081 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4082 make_dev_alias(dev, "stderr");
4085 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);