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");
109 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
111 MALLOC_DECLARE(M_FADVISE);
113 static uma_zone_t file_zone;
115 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
117 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
118 struct thread *td, int holdleaders);
119 static int fd_first_free(struct filedesc *fdp, int low, int size);
120 static int fd_last_used(struct filedesc *fdp, int size);
121 static void fdgrowtable(struct filedesc *fdp, int nfd);
122 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
123 static void fdunused(struct filedesc *fdp, int fd);
124 static void fdused(struct filedesc *fdp, int fd);
125 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
126 static int fill_procdesc_info(struct procdesc *pdp,
127 struct kinfo_file *kif);
128 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
129 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
130 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
131 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
132 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
133 static int getmaxfd(struct proc *p);
138 * - An array of open file descriptors (fd_ofiles)
139 * - An array of file flags (fd_ofileflags)
140 * - A bitmap recording which descriptors are in use (fd_map)
142 * A process starts out with NDFILE descriptors. The value of NDFILE has
143 * been selected based the historical limit of 20 open files, and an
144 * assumption that the majority of processes, especially short-lived
145 * processes like shells, will never need more.
147 * If this initial allocation is exhausted, a larger descriptor table and
148 * map are allocated dynamically, and the pointers in the process's struct
149 * filedesc are updated to point to those. This is repeated every time
150 * the process runs out of file descriptors (provided it hasn't hit its
153 * Since threads may hold references to individual descriptor table
154 * entries, the tables are never freed. Instead, they are placed on a
155 * linked list and freed only when the struct filedesc is released.
158 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
159 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
160 #define NDSLOT(x) ((x) / NDENTRIES)
161 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
162 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
165 * SLIST entry used to keep track of ofiles which must be reclaimed when
169 struct filedescent *ft_table;
170 SLIST_ENTRY(freetable) ft_next;
174 * Initial allocation: a filedesc structure + the head of SLIST used to
175 * keep track of old ofiles + enough space for NDFILE descriptors.
178 struct filedesc fd_fd;
179 SLIST_HEAD(, freetable) fd_free;
180 struct filedescent fd_dfiles[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 * If low >= size, just return low. Otherwise find the first zero bit in the
196 * given bitmap, starting at low and not exceeding size - 1. Return size if
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 0 and
224 * not exceeding size - 1. Return -1 if not found.
227 fd_last_used(struct filedesc *fdp, int size)
229 NDSLOTTYPE *map = fdp->fd_map;
234 if (size % NDENTRIES) {
235 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
236 if ((mask &= map[off]) != 0)
237 return (off * NDENTRIES + flsl(mask) - 1);
240 for (minoff = NDSLOT(0); off >= minoff; --off)
242 return (off * NDENTRIES + flsl(map[off]) - 1);
247 fdisused(struct filedesc *fdp, int fd)
250 FILEDESC_LOCK_ASSERT(fdp);
252 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
253 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
255 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
259 * Mark a file descriptor as used.
262 fdused(struct filedesc *fdp, int fd)
265 FILEDESC_XLOCK_ASSERT(fdp);
267 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
269 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
270 if (fd > fdp->fd_lastfile)
271 fdp->fd_lastfile = fd;
272 if (fd == fdp->fd_freefile)
273 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
277 * Mark a file descriptor as unused.
280 fdunused(struct filedesc *fdp, int fd)
283 FILEDESC_XLOCK_ASSERT(fdp);
285 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
286 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
287 ("fd=%d is still in use", fd));
289 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
290 if (fd < fdp->fd_freefile)
291 fdp->fd_freefile = fd;
292 if (fd == fdp->fd_lastfile)
293 fdp->fd_lastfile = fd_last_used(fdp, fd);
297 * Free a file descriptor.
299 * Avoid some work if fdp is about to be destroyed.
302 _fdfree(struct filedesc *fdp, int fd, int last)
304 struct filedescent *fde;
306 fde = &fdp->fd_ofiles[fd];
307 filecaps_free(&fde->fde_caps);
310 bzero(fde, sizeof(*fde));
315 fdfree(struct filedesc *fdp, int fd)
322 fdfree_last(struct filedesc *fdp, int fd)
329 * System calls on descriptors.
331 #ifndef _SYS_SYSPROTO_H_
332 struct getdtablesize_args {
338 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
340 struct proc *p = td->td_proc;
345 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
346 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
348 if (lim < td->td_retval[0])
349 td->td_retval[0] = lim;
354 * Duplicate a file descriptor to a particular value.
356 * Note: keep in mind that a potential race condition exists when closing
357 * descriptors from a shared descriptor table (via rfork).
359 #ifndef _SYS_SYSPROTO_H_
367 sys_dup2(struct thread *td, struct dup2_args *uap)
370 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
375 * Duplicate a file descriptor.
377 #ifndef _SYS_SYSPROTO_H_
384 sys_dup(struct thread *td, struct dup_args *uap)
387 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
391 * The file control system call.
393 #ifndef _SYS_SYSPROTO_H_
402 sys_fcntl(struct thread *td, struct fcntl_args *uap)
405 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
409 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
422 * Convert old flock structure to new.
424 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
425 fl.l_start = ofl.l_start;
426 fl.l_len = ofl.l_len;
427 fl.l_pid = ofl.l_pid;
428 fl.l_type = ofl.l_type;
429 fl.l_whence = ofl.l_whence;
443 arg1 = (intptr_t)&fl;
449 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
450 arg1 = (intptr_t)&fl;
458 error = kern_fcntl(td, fd, cmd, arg1);
461 if (cmd == F_OGETLK) {
462 ofl.l_start = fl.l_start;
463 ofl.l_len = fl.l_len;
464 ofl.l_pid = fl.l_pid;
465 ofl.l_type = fl.l_type;
466 ofl.l_whence = fl.l_whence;
467 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
468 } else if (cmd == F_GETLK) {
469 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
475 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
477 struct filedesc *fdp;
479 struct file *fp, *fp2;
480 struct filedescent *fde;
496 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
499 case F_DUPFD_CLOEXEC:
501 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
507 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
510 case F_DUP2FD_CLOEXEC:
512 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
518 if ((fp = fget_locked(fdp, fd)) == NULL) {
519 FILEDESC_SUNLOCK(fdp);
523 fde = &fdp->fd_ofiles[fd];
525 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
526 FILEDESC_SUNLOCK(fdp);
531 if ((fp = fget_locked(fdp, fd)) == NULL) {
532 FILEDESC_XUNLOCK(fdp);
536 fde = &fdp->fd_ofiles[fd];
537 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
538 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
539 FILEDESC_XUNLOCK(fdp);
543 error = fget_unlocked(fdp, fd,
544 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
547 td->td_retval[0] = OFLAGS(fp->f_flag);
552 error = fget_unlocked(fdp, fd,
553 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
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);
580 error = fget_unlocked(fdp, fd,
581 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
584 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
586 td->td_retval[0] = tmp;
591 error = fget_unlocked(fdp, fd,
592 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
596 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
601 error = priv_check(td, PRIV_NFS_LOCKD);
609 /* FALLTHROUGH F_SETLK */
613 cap_rights_init(&rights, CAP_FLOCK);
614 error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
617 if (fp->f_type != DTYPE_VNODE) {
623 flp = (struct flock *)arg;
624 if (flp->l_whence == SEEK_CUR) {
625 foffset = foffset_get(fp);
628 foffset > OFF_MAX - flp->l_start)) {
629 FILEDESC_SUNLOCK(fdp);
634 flp->l_start += foffset;
638 switch (flp->l_type) {
640 if ((fp->f_flag & FREAD) == 0) {
644 PROC_LOCK(p->p_leader);
645 p->p_leader->p_flag |= P_ADVLOCK;
646 PROC_UNLOCK(p->p_leader);
647 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
651 if ((fp->f_flag & FWRITE) == 0) {
655 PROC_LOCK(p->p_leader);
656 p->p_leader->p_flag |= P_ADVLOCK;
657 PROC_UNLOCK(p->p_leader);
658 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
662 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
667 * Temporary api for testing remote lock
670 if (flg != F_REMOTE) {
674 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
675 F_UNLCKSYS, flp, flg);
681 if (error != 0 || flp->l_type == F_UNLCK ||
682 flp->l_type == F_UNLCKSYS) {
688 * Check for a race with close.
690 * The vnode is now advisory locked (or unlocked, but this case
691 * is not really important) as the caller requested.
692 * We had to drop the filedesc lock, so we need to recheck if
693 * the descriptor is still valid, because if it was closed
694 * in the meantime we need to remove advisory lock from the
695 * vnode - close on any descriptor leading to an advisory
696 * locked vnode, removes that lock.
697 * We will return 0 on purpose in that case, as the result of
698 * successful advisory lock might have been externally visible
699 * already. This is fine - effectively we pretend to the caller
700 * that the closing thread was a bit slower and that the
701 * advisory lock succeeded before the close.
703 error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
709 flp->l_whence = SEEK_SET;
712 flp->l_type = F_UNLCK;
713 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
714 F_UNLCK, flp, F_POSIX);
721 error = fget_unlocked(fdp, fd,
722 cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
725 if (fp->f_type != DTYPE_VNODE) {
730 flp = (struct flock *)arg;
731 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
732 flp->l_type != F_UNLCK) {
737 if (flp->l_whence == SEEK_CUR) {
738 foffset = foffset_get(fp);
739 if ((flp->l_start > 0 &&
740 foffset > OFF_MAX - flp->l_start) ||
742 foffset < OFF_MIN - flp->l_start)) {
743 FILEDESC_SUNLOCK(fdp);
748 flp->l_start += foffset;
751 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
757 arg = arg ? 128 * 1024: 0;
760 error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
763 if (fp->f_type != DTYPE_VNODE) {
770 * Exclusive lock synchronizes against f_seqcount reads and
771 * writes in sequential_heuristic().
773 error = vn_lock(vp, LK_EXCLUSIVE);
779 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
780 fp->f_seqcount = (arg + bsize - 1) / bsize;
781 atomic_set_int(&fp->f_flag, FRDAHEAD);
783 atomic_clear_int(&fp->f_flag, FRDAHEAD);
797 getmaxfd(struct proc *p)
802 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
809 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
812 do_dup(struct thread *td, int flags, int old, int new,
815 struct filedesc *fdp;
816 struct filedescent *oldfde, *newfde;
826 * Verify we have a valid descriptor to dup from and possibly to
827 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
828 * return EINVAL when the new descriptor is out of bounds.
833 return (flags & DUP_FCNTL ? EINVAL : EBADF);
836 return (flags & DUP_FCNTL ? EINVAL : EBADF);
839 if (fget_locked(fdp, old) == NULL) {
840 FILEDESC_XUNLOCK(fdp);
843 oldfde = &fdp->fd_ofiles[old];
844 if (flags & DUP_FIXED && old == new) {
846 if (flags & DUP_CLOEXEC)
847 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
848 FILEDESC_XUNLOCK(fdp);
851 fp = oldfde->fde_file;
855 * If the caller specified a file descriptor, make sure the file
856 * table is large enough to hold it, and grab it. Otherwise, just
857 * allocate a new descriptor the usual way.
859 if (flags & DUP_FIXED) {
860 if (new >= fdp->fd_nfiles) {
862 * The resource limits are here instead of e.g.
863 * fdalloc(), because the file descriptor table may be
864 * shared between processes, so we can't really use
865 * racct_add()/racct_sub(). Instead of counting the
866 * number of actually allocated descriptors, just put
867 * the limit on the size of the file descriptor table.
871 error = racct_set(p, RACCT_NOFILE, new + 1);
874 FILEDESC_XUNLOCK(fdp);
879 fdgrowtable_exp(fdp, new + 1);
880 oldfde = &fdp->fd_ofiles[old];
882 newfde = &fdp->fd_ofiles[new];
883 if (newfde->fde_file == NULL)
886 if ((error = fdalloc(td, new, &new)) != 0) {
887 FILEDESC_XUNLOCK(fdp);
891 newfde = &fdp->fd_ofiles[new];
894 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
895 KASSERT(old != new, ("new fd is same as old"));
897 delfp = newfde->fde_file;
900 * Duplicate the source descriptor.
902 filecaps_free(&newfde->fde_caps);
904 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
905 if ((flags & DUP_CLOEXEC) != 0)
906 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
908 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
912 (void) closefp(fdp, new, delfp, td, 1);
913 /* closefp() drops the FILEDESC lock for us. */
915 FILEDESC_XUNLOCK(fdp);
922 * If sigio is on the list associated with a process or process group,
923 * disable signalling from the device, remove sigio from the list and
927 funsetown(struct sigio **sigiop)
937 *(sigio->sio_myref) = NULL;
938 if ((sigio)->sio_pgid < 0) {
939 struct pgrp *pg = (sigio)->sio_pgrp;
941 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
945 struct proc *p = (sigio)->sio_proc;
947 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
952 crfree(sigio->sio_ucred);
953 free(sigio, M_SIGIO);
957 * Free a list of sigio structures.
958 * We only need to lock the SIGIO_LOCK because we have made ourselves
959 * inaccessible to callers of fsetown and therefore do not need to lock
960 * the proc or pgrp struct for the list manipulation.
963 funsetownlst(struct sigiolst *sigiolst)
969 sigio = SLIST_FIRST(sigiolst);
976 * Every entry of the list should belong
977 * to a single proc or pgrp.
979 if (sigio->sio_pgid < 0) {
980 pg = sigio->sio_pgrp;
981 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
982 } else /* if (sigio->sio_pgid > 0) */ {
984 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
988 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
989 *(sigio->sio_myref) = NULL;
991 KASSERT(sigio->sio_pgid < 0,
992 ("Proc sigio in pgrp sigio list"));
993 KASSERT(sigio->sio_pgrp == pg,
994 ("Bogus pgrp in sigio list"));
996 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
999 } else /* if (p != NULL) */ {
1000 KASSERT(sigio->sio_pgid > 0,
1001 ("Pgrp sigio in proc sigio list"));
1002 KASSERT(sigio->sio_proc == p,
1003 ("Bogus proc in sigio list"));
1005 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1010 crfree(sigio->sio_ucred);
1011 free(sigio, M_SIGIO);
1018 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1020 * After permission checking, add a sigio structure to the sigio list for
1021 * the process or process group.
1024 fsetown(pid_t pgid, struct sigio **sigiop)
1028 struct sigio *sigio;
1038 /* Allocate and fill in the new sigio out of locks. */
1039 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1040 sigio->sio_pgid = pgid;
1041 sigio->sio_ucred = crhold(curthread->td_ucred);
1042 sigio->sio_myref = sigiop;
1044 sx_slock(&proctree_lock);
1053 * Policy - Don't allow a process to FSETOWN a process
1054 * in another session.
1056 * Remove this test to allow maximum flexibility or
1057 * restrict FSETOWN to the current process or process
1058 * group for maximum safety.
1061 if (proc->p_session != curthread->td_proc->p_session) {
1067 } else /* if (pgid < 0) */ {
1068 pgrp = pgfind(-pgid);
1076 * Policy - Don't allow a process to FSETOWN a process
1077 * in another session.
1079 * Remove this test to allow maximum flexibility or
1080 * restrict FSETOWN to the current process or process
1081 * group for maximum safety.
1083 if (pgrp->pg_session != curthread->td_proc->p_session) {
1094 * Since funsetownlst() is called without the proctree
1095 * locked, we need to check for P_WEXIT.
1096 * XXX: is ESRCH correct?
1098 if ((proc->p_flag & P_WEXIT) != 0) {
1103 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1104 sigio->sio_proc = proc;
1108 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1109 sigio->sio_pgrp = pgrp;
1112 sx_sunlock(&proctree_lock);
1119 sx_sunlock(&proctree_lock);
1120 crfree(sigio->sio_ucred);
1121 free(sigio, M_SIGIO);
1126 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1130 struct sigio **sigiop;
1135 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1141 * Function drops the filedesc lock on return.
1144 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1149 FILEDESC_XLOCK_ASSERT(fdp);
1152 if (td->td_proc->p_fdtol != NULL) {
1154 * Ask fdfree() to sleep to ensure that all relevant
1155 * process leaders can be traversed in closef().
1157 fdp->fd_holdleaderscount++;
1164 * We now hold the fp reference that used to be owned by the
1165 * descriptor array. We have to unlock the FILEDESC *AFTER*
1166 * knote_fdclose to prevent a race of the fd getting opened, a knote
1167 * added, and deleteing a knote for the new fd.
1169 knote_fdclose(td, fd);
1172 * We need to notify mqueue if the object is of type mqueue.
1174 if (fp->f_type == DTYPE_MQUEUE)
1175 mq_fdclose(td, fd, fp);
1176 FILEDESC_XUNLOCK(fdp);
1178 error = closef(fp, td);
1180 FILEDESC_XLOCK(fdp);
1181 fdp->fd_holdleaderscount--;
1182 if (fdp->fd_holdleaderscount == 0 &&
1183 fdp->fd_holdleaderswakeup != 0) {
1184 fdp->fd_holdleaderswakeup = 0;
1185 wakeup(&fdp->fd_holdleaderscount);
1187 FILEDESC_XUNLOCK(fdp);
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;
1218 fdp = td->td_proc->p_fd;
1220 AUDIT_SYSCLOSE(td, fd);
1222 FILEDESC_XLOCK(fdp);
1223 if ((fp = fget_locked(fdp, fd)) == NULL) {
1224 FILEDESC_XUNLOCK(fdp);
1229 /* closefp() drops the FILEDESC lock for us. */
1230 return (closefp(fdp, fd, fp, td, 1));
1234 * Close open file descriptors.
1236 #ifndef _SYS_SYSPROTO_H_
1237 struct closefrom_args {
1243 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1245 struct filedesc *fdp;
1248 fdp = td->td_proc->p_fd;
1249 AUDIT_ARG_FD(uap->lowfd);
1252 * Treat negative starting file descriptor values identical to
1253 * closefrom(0) which closes all files.
1257 FILEDESC_SLOCK(fdp);
1258 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1259 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1260 FILEDESC_SUNLOCK(fdp);
1261 (void)kern_close(td, fd);
1262 FILEDESC_SLOCK(fdp);
1265 FILEDESC_SUNLOCK(fdp);
1269 #if defined(COMPAT_43)
1271 * Return status information about a file descriptor.
1273 #ifndef _SYS_SYSPROTO_H_
1274 struct ofstat_args {
1281 ofstat(struct thread *td, struct ofstat_args *uap)
1287 error = kern_fstat(td, uap->fd, &ub);
1290 error = copyout(&oub, uap->sb, sizeof(oub));
1294 #endif /* COMPAT_43 */
1297 * Return status information about a file descriptor.
1299 #ifndef _SYS_SYSPROTO_H_
1307 sys_fstat(struct thread *td, struct fstat_args *uap)
1312 error = kern_fstat(td, uap->fd, &ub);
1314 error = copyout(&ub, uap->sb, sizeof(ub));
1319 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1322 cap_rights_t rights;
1327 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1331 AUDIT_ARG_FILE(td->td_proc, fp);
1333 error = fo_stat(fp, sbp, td->td_ucred, td);
1336 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1343 * Return status information about a file descriptor.
1345 #ifndef _SYS_SYSPROTO_H_
1346 struct nfstat_args {
1353 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1359 error = kern_fstat(td, uap->fd, &ub);
1361 cvtnstat(&ub, &nub);
1362 error = copyout(&nub, uap->sb, sizeof(nub));
1368 * Return pathconf information about a file descriptor.
1370 #ifndef _SYS_SYSPROTO_H_
1371 struct fpathconf_args {
1378 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1382 cap_rights_t rights;
1385 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1389 /* If asynchronous I/O is available, it works for all descriptors. */
1390 if (uap->name == _PC_ASYNC_IO) {
1391 td->td_retval[0] = async_io_version;
1396 vn_lock(vp, LK_SHARED | LK_RETRY);
1397 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1399 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1400 if (uap->name != _PC_PIPE_BUF) {
1403 td->td_retval[0] = PIPE_BUF;
1415 * Initialize filecaps structure.
1418 filecaps_init(struct filecaps *fcaps)
1421 bzero(fcaps, sizeof(*fcaps));
1422 fcaps->fc_nioctls = -1;
1426 * Copy filecaps structure allocating memory for ioctls array if needed.
1429 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1434 if (src->fc_ioctls != NULL) {
1435 KASSERT(src->fc_nioctls > 0,
1436 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1438 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1439 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1440 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1445 * Move filecaps structure to the new place and clear the old place.
1448 filecaps_move(struct filecaps *src, struct filecaps *dst)
1452 bzero(src, sizeof(*src));
1456 * Fill the given filecaps structure with full rights.
1459 filecaps_fill(struct filecaps *fcaps)
1462 CAP_ALL(&fcaps->fc_rights);
1463 fcaps->fc_ioctls = NULL;
1464 fcaps->fc_nioctls = -1;
1465 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1469 * Free memory allocated within filecaps structure.
1472 filecaps_free(struct filecaps *fcaps)
1475 free(fcaps->fc_ioctls, M_FILECAPS);
1476 bzero(fcaps, sizeof(*fcaps));
1480 * Validate the given filecaps structure.
1483 filecaps_validate(const struct filecaps *fcaps, const char *func)
1486 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1487 ("%s: invalid rights", func));
1488 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1489 ("%s: invalid fcntls", func));
1490 KASSERT(fcaps->fc_fcntls == 0 ||
1491 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1492 ("%s: fcntls without CAP_FCNTL", func));
1493 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1494 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1495 ("%s: invalid ioctls", func));
1496 KASSERT(fcaps->fc_nioctls == 0 ||
1497 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1498 ("%s: ioctls without CAP_IOCTL", func));
1502 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1506 FILEDESC_XLOCK_ASSERT(fdp);
1508 nfd1 = fdp->fd_nfiles * 2;
1511 fdgrowtable(fdp, nfd1);
1515 * Grow the file table to accomodate (at least) nfd descriptors.
1518 fdgrowtable(struct filedesc *fdp, int nfd)
1520 struct filedesc0 *fdp0;
1521 struct freetable *ft;
1522 struct filedescent *ntable;
1523 struct filedescent *otable;
1524 int nnfiles, onfiles;
1525 NDSLOTTYPE *nmap, *omap;
1527 FILEDESC_XLOCK_ASSERT(fdp);
1529 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1531 /* save old values */
1532 onfiles = fdp->fd_nfiles;
1533 otable = fdp->fd_ofiles;
1536 /* compute the size of the new table */
1537 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1538 if (nnfiles <= onfiles)
1539 /* the table is already large enough */
1543 * Allocate a new table. We need enough space for the
1544 * file entries themselves and the struct freetable we will use
1545 * when we decommission the table and place it on the freelist.
1546 * We place the struct freetable in the middle so we don't have
1547 * to worry about padding.
1549 ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1550 M_FILEDESC, M_ZERO | M_WAITOK);
1551 /* copy the old data over and point at the new tables */
1552 memcpy(ntable, otable, onfiles * sizeof(*otable));
1553 fdp->fd_ofiles = ntable;
1556 * Allocate a new map only if the old is not large enough. It will
1557 * grow at a slower rate than the table as it can map more
1558 * entries than the table can hold.
1560 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1561 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1563 /* copy over the old data and update the pointer */
1564 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1569 * In order to have a valid pattern for fget_unlocked()
1570 * fdp->fd_nfiles must be the last member to be updated, otherwise
1571 * fget_unlocked() consumers may reference a new, higher value for
1572 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1573 * resulting in OOB accesses.
1575 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1578 * Do not free the old file table, as some threads may still
1579 * reference entries within it. Instead, place it on a freelist
1580 * which will be processed when the struct filedesc is released.
1582 * Note that if onfiles == NDFILE, we're dealing with the original
1583 * static allocation contained within (struct filedesc0 *)fdp,
1584 * which must not be freed.
1586 if (onfiles > NDFILE) {
1587 ft = (struct freetable *)&otable[onfiles];
1588 fdp0 = (struct filedesc0 *)fdp;
1589 ft->ft_table = otable;
1590 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1593 * The map does not have the same possibility of threads still
1594 * holding references to it. So always free it as long as it
1595 * does not reference the original static allocation.
1597 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1598 free(omap, M_FILEDESC);
1602 * Allocate a file descriptor for the process.
1605 fdalloc(struct thread *td, int minfd, int *result)
1607 struct proc *p = td->td_proc;
1608 struct filedesc *fdp = p->p_fd;
1609 int fd = -1, maxfd, allocfd;
1614 FILEDESC_XLOCK_ASSERT(fdp);
1616 if (fdp->fd_freefile > minfd)
1617 minfd = fdp->fd_freefile;
1619 maxfd = getmaxfd(p);
1622 * Search the bitmap for a free descriptor starting at minfd.
1623 * If none is found, grow the file table.
1625 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1628 if (fd >= fdp->fd_nfiles) {
1629 allocfd = min(fd * 2, maxfd);
1632 error = racct_set(p, RACCT_NOFILE, allocfd);
1638 * fd is already equal to first free descriptor >= minfd, so
1639 * we only need to grow the table and we are done.
1641 fdgrowtable_exp(fdp, allocfd);
1645 * Perform some sanity checks, then mark the file descriptor as
1646 * used and return it to the caller.
1648 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1649 ("invalid descriptor %d", fd));
1650 KASSERT(!fdisused(fdp, fd),
1651 ("fd_first_free() returned non-free descriptor"));
1652 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1653 ("file descriptor isn't free"));
1654 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1661 * Allocate n file descriptors for the process.
1664 fdallocn(struct thread *td, int minfd, int *fds, int n)
1666 struct proc *p = td->td_proc;
1667 struct filedesc *fdp = p->p_fd;
1670 FILEDESC_XLOCK_ASSERT(fdp);
1672 if (!fdavail(td, n))
1675 for (i = 0; i < n; i++)
1676 if (fdalloc(td, 0, &fds[i]) != 0)
1680 for (i--; i >= 0; i--)
1681 fdunused(fdp, fds[i]);
1689 * Check to see whether n user file descriptors are available to the process
1693 fdavail(struct thread *td, int n)
1695 struct proc *p = td->td_proc;
1696 struct filedesc *fdp = td->td_proc->p_fd;
1699 FILEDESC_LOCK_ASSERT(fdp);
1702 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1703 * call racct_add() from there instead of dealing with containers
1707 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1709 last = min(fdp->fd_nfiles, lim);
1710 for (i = fdp->fd_freefile; i < last; i++) {
1711 if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1718 * Create a new open file structure and allocate a file decriptor for the
1719 * process that refers to it. We add one reference to the file for the
1720 * descriptor table and one reference for resultfp. This is to prevent us
1721 * being preempted and the entry in the descriptor table closed after we
1722 * release the FILEDESC lock.
1725 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1730 error = falloc_noinstall(td, &fp);
1732 return (error); /* no reference held on error */
1734 error = finstall(td, fp, &fd, flags, NULL);
1736 fdrop(fp, td); /* one reference (fp only) */
1740 if (resultfp != NULL)
1741 *resultfp = fp; /* copy out result */
1743 fdrop(fp, td); /* release local reference */
1745 if (resultfd != NULL)
1752 * Create a new open file structure without allocating a file descriptor.
1755 falloc_noinstall(struct thread *td, struct file **resultfp)
1758 int maxuserfiles = maxfiles - (maxfiles / 20);
1759 static struct timeval lastfail;
1762 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1764 if ((openfiles >= maxuserfiles &&
1765 priv_check(td, PRIV_MAXFILES) != 0) ||
1766 openfiles >= maxfiles) {
1767 if (ppsratecheck(&lastfail, &curfail, 1)) {
1768 printf("kern.maxfiles limit exceeded by uid %i, "
1769 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1773 atomic_add_int(&openfiles, 1);
1774 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1775 refcount_init(&fp->f_count, 1);
1776 fp->f_cred = crhold(td->td_ucred);
1777 fp->f_ops = &badfileops;
1785 * Install a file in a file descriptor table.
1788 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1789 struct filecaps *fcaps)
1791 struct filedesc *fdp = td->td_proc->p_fd;
1792 struct filedescent *fde;
1795 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1796 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1798 filecaps_validate(fcaps, __func__);
1800 FILEDESC_XLOCK(fdp);
1801 if ((error = fdalloc(td, 0, fd))) {
1802 FILEDESC_XUNLOCK(fdp);
1806 fde = &fdp->fd_ofiles[*fd];
1808 if ((flags & O_CLOEXEC) != 0)
1809 fde->fde_flags |= UF_EXCLOSE;
1811 filecaps_move(fcaps, &fde->fde_caps);
1813 filecaps_fill(&fde->fde_caps);
1814 FILEDESC_XUNLOCK(fdp);
1819 * Build a new filedesc structure from another.
1820 * Copy the current, root, and jail root vnode references.
1823 fdinit(struct filedesc *fdp)
1825 struct filedesc0 *newfdp;
1827 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1828 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1830 FILEDESC_SLOCK(fdp);
1831 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1832 if (newfdp->fd_fd.fd_cdir)
1833 VREF(newfdp->fd_fd.fd_cdir);
1834 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1835 if (newfdp->fd_fd.fd_rdir)
1836 VREF(newfdp->fd_fd.fd_rdir);
1837 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1838 if (newfdp->fd_fd.fd_jdir)
1839 VREF(newfdp->fd_fd.fd_jdir);
1840 FILEDESC_SUNLOCK(fdp);
1843 /* Create the file descriptor table. */
1844 newfdp->fd_fd.fd_refcnt = 1;
1845 newfdp->fd_fd.fd_holdcnt = 1;
1846 newfdp->fd_fd.fd_cmask = CMASK;
1847 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1848 newfdp->fd_fd.fd_nfiles = NDFILE;
1849 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1850 newfdp->fd_fd.fd_lastfile = -1;
1851 return (&newfdp->fd_fd);
1854 static struct filedesc *
1855 fdhold(struct proc *p)
1857 struct filedesc *fdp;
1859 mtx_lock(&fdesc_mtx);
1863 mtx_unlock(&fdesc_mtx);
1868 fddrop(struct filedesc *fdp)
1870 struct filedesc0 *fdp0;
1871 struct freetable *ft;
1874 mtx_lock(&fdesc_mtx);
1875 i = --fdp->fd_holdcnt;
1876 mtx_unlock(&fdesc_mtx);
1880 FILEDESC_LOCK_DESTROY(fdp);
1881 fdp0 = (struct filedesc0 *)fdp;
1882 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1883 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1884 free(ft->ft_table, M_FILEDESC);
1886 free(fdp, M_FILEDESC);
1890 * Share a filedesc structure.
1893 fdshare(struct filedesc *fdp)
1896 FILEDESC_XLOCK(fdp);
1898 FILEDESC_XUNLOCK(fdp);
1903 * Unshare a filedesc structure, if necessary by making a copy
1906 fdunshare(struct thread *td)
1908 struct filedesc *tmp;
1909 struct proc *p = td->td_proc;
1911 if (p->p_fd->fd_refcnt == 1)
1914 tmp = fdcopy(p->p_fd);
1920 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1921 * this is to ease callers, not catch errors.
1924 fdcopy(struct filedesc *fdp)
1926 struct filedesc *newfdp;
1927 struct filedescent *nfde, *ofde;
1930 /* Certain daemons might not have file descriptors. */
1934 newfdp = fdinit(fdp);
1935 FILEDESC_SLOCK(fdp);
1936 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1937 FILEDESC_SUNLOCK(fdp);
1938 FILEDESC_XLOCK(newfdp);
1939 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1940 FILEDESC_XUNLOCK(newfdp);
1941 FILEDESC_SLOCK(fdp);
1943 /* copy all passable descriptors (i.e. not kqueue) */
1944 newfdp->fd_freefile = -1;
1945 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1946 ofde = &fdp->fd_ofiles[i];
1947 if (fdisused(fdp, i) &&
1948 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1949 ofde->fde_file->f_ops != &badfileops) {
1950 nfde = &newfdp->fd_ofiles[i];
1952 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1953 fhold(nfde->fde_file);
1954 newfdp->fd_lastfile = i;
1956 if (newfdp->fd_freefile == -1)
1957 newfdp->fd_freefile = i;
1960 newfdp->fd_cmask = fdp->fd_cmask;
1961 FILEDESC_SUNLOCK(fdp);
1962 FILEDESC_XLOCK(newfdp);
1963 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1964 if (newfdp->fd_ofiles[i].fde_file != NULL)
1967 if (newfdp->fd_freefile == -1)
1968 newfdp->fd_freefile = i;
1969 FILEDESC_XUNLOCK(newfdp);
1974 * Release a filedesc structure.
1977 fdescfree(struct thread *td)
1979 struct filedesc *fdp;
1981 struct filedesc_to_leader *fdtol;
1983 struct vnode *cdir, *jdir, *rdir, *vp;
1986 /* Certain daemons might not have file descriptors. */
1987 fdp = td->td_proc->p_fd;
1992 PROC_LOCK(td->td_proc);
1993 racct_set(td->td_proc, RACCT_NOFILE, 0);
1994 PROC_UNLOCK(td->td_proc);
1997 /* Check for special need to clear POSIX style locks */
1998 fdtol = td->td_proc->p_fdtol;
1999 if (fdtol != NULL) {
2000 FILEDESC_XLOCK(fdp);
2001 KASSERT(fdtol->fdl_refcount > 0,
2002 ("filedesc_to_refcount botch: fdl_refcount=%d",
2003 fdtol->fdl_refcount));
2004 if (fdtol->fdl_refcount == 1 &&
2005 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2006 for (i = 0; i <= fdp->fd_lastfile; i++) {
2007 fp = fdp->fd_ofiles[i].fde_file;
2008 if (fp == NULL || fp->f_type != DTYPE_VNODE)
2011 FILEDESC_XUNLOCK(fdp);
2012 lf.l_whence = SEEK_SET;
2015 lf.l_type = F_UNLCK;
2017 (void) VOP_ADVLOCK(vp,
2018 (caddr_t)td->td_proc->p_leader, F_UNLCK,
2020 FILEDESC_XLOCK(fdp);
2025 if (fdtol->fdl_refcount == 1) {
2026 if (fdp->fd_holdleaderscount > 0 &&
2027 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2029 * close() or do_dup() has cleared a reference
2030 * in a shared file descriptor table.
2032 fdp->fd_holdleaderswakeup = 1;
2033 sx_sleep(&fdp->fd_holdleaderscount,
2034 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2037 if (fdtol->fdl_holdcount > 0) {
2039 * Ensure that fdtol->fdl_leader remains
2040 * valid in closef().
2042 fdtol->fdl_wakeup = 1;
2043 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2048 fdtol->fdl_refcount--;
2049 if (fdtol->fdl_refcount == 0 &&
2050 fdtol->fdl_holdcount == 0) {
2051 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2052 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2055 td->td_proc->p_fdtol = NULL;
2056 FILEDESC_XUNLOCK(fdp);
2058 free(fdtol, M_FILEDESC_TO_LEADER);
2061 mtx_lock(&fdesc_mtx);
2062 td->td_proc->p_fd = NULL;
2063 mtx_unlock(&fdesc_mtx);
2065 FILEDESC_XLOCK(fdp);
2066 i = --fdp->fd_refcnt;
2068 FILEDESC_XUNLOCK(fdp);
2072 cdir = fdp->fd_cdir;
2073 fdp->fd_cdir = NULL;
2074 rdir = fdp->fd_rdir;
2075 fdp->fd_rdir = NULL;
2076 jdir = fdp->fd_jdir;
2077 fdp->fd_jdir = NULL;
2078 FILEDESC_XUNLOCK(fdp);
2080 for (i = 0; i <= fdp->fd_lastfile; i++) {
2081 fp = fdp->fd_ofiles[i].fde_file;
2083 fdfree_last(fdp, i);
2084 (void) closef(fp, td);
2088 if (fdp->fd_nfiles > NDFILE)
2089 free(fdp->fd_ofiles, M_FILEDESC);
2090 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2091 free(fdp->fd_map, M_FILEDESC);
2104 * For setugid programs, we don't want to people to use that setugidness
2105 * to generate error messages which write to a file which otherwise would
2106 * otherwise be off-limits to the process. We check for filesystems where
2107 * the vnode can change out from under us after execve (like [lin]procfs).
2109 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2110 * sufficient. We also don't check for setugidness since we know we are.
2113 is_unsafe(struct file *fp)
2115 if (fp->f_type == DTYPE_VNODE) {
2116 struct vnode *vp = fp->f_vnode;
2118 if ((vp->v_vflag & VV_PROCDEP) != 0)
2125 * Make this setguid thing safe, if at all possible.
2128 setugidsafety(struct thread *td)
2130 struct filedesc *fdp;
2134 fdp = td->td_proc->p_fd;
2135 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2136 FILEDESC_XLOCK(fdp);
2137 for (i = 0; i <= fdp->fd_lastfile; i++) {
2140 fp = fdp->fd_ofiles[i].fde_file;
2141 if (fp != NULL && is_unsafe(fp)) {
2142 knote_fdclose(td, i);
2144 * NULL-out descriptor prior to close to avoid
2145 * a race while close blocks.
2148 FILEDESC_XUNLOCK(fdp);
2149 (void) closef(fp, td);
2150 FILEDESC_XLOCK(fdp);
2153 FILEDESC_XUNLOCK(fdp);
2157 * If a specific file object occupies a specific file descriptor, close the
2158 * file descriptor entry and drop a reference on the file object. This is a
2159 * convenience function to handle a subsequent error in a function that calls
2160 * falloc() that handles the race that another thread might have closed the
2161 * file descriptor out from under the thread creating the file object.
2164 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2167 FILEDESC_XLOCK(fdp);
2168 if (fdp->fd_ofiles[idx].fde_file == fp) {
2170 FILEDESC_XUNLOCK(fdp);
2173 FILEDESC_XUNLOCK(fdp);
2177 * Close any files on exec?
2180 fdcloseexec(struct thread *td)
2182 struct filedesc *fdp;
2183 struct filedescent *fde;
2187 fdp = td->td_proc->p_fd;
2188 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2189 FILEDESC_XLOCK(fdp);
2190 for (i = 0; i <= fdp->fd_lastfile; i++) {
2191 fde = &fdp->fd_ofiles[i];
2193 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2194 (fde->fde_flags & UF_EXCLOSE))) {
2196 (void) closefp(fdp, i, fp, td, 0);
2197 /* closefp() drops the FILEDESC lock. */
2198 FILEDESC_XLOCK(fdp);
2201 FILEDESC_XUNLOCK(fdp);
2205 * It is unsafe for set[ug]id processes to be started with file
2206 * descriptors 0..2 closed, as these descriptors are given implicit
2207 * significance in the Standard C library. fdcheckstd() will create a
2208 * descriptor referencing /dev/null for each of stdin, stdout, and
2209 * stderr that is not already open.
2212 fdcheckstd(struct thread *td)
2214 struct filedesc *fdp;
2215 register_t retval, save;
2216 int i, error, devnull;
2218 fdp = td->td_proc->p_fd;
2219 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2222 for (i = 0; i < 3; i++) {
2223 if (fdp->fd_ofiles[i].fde_file != NULL)
2226 save = td->td_retval[0];
2227 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2229 devnull = td->td_retval[0];
2230 td->td_retval[0] = save;
2233 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2235 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2244 * Internal form of close. Decrement reference count on file structure.
2245 * Note: td may be NULL when closing a file that was being passed in a
2248 * XXXRW: Giant is not required for the caller, but often will be held; this
2249 * makes it moderately likely the Giant will be recursed in the VFS case.
2252 closef(struct file *fp, struct thread *td)
2256 struct filedesc_to_leader *fdtol;
2257 struct filedesc *fdp;
2260 * POSIX record locking dictates that any close releases ALL
2261 * locks owned by this process. This is handled by setting
2262 * a flag in the unlock to free ONLY locks obeying POSIX
2263 * semantics, and not to free BSD-style file locks.
2264 * If the descriptor was in a message, POSIX-style locks
2265 * aren't passed with the descriptor, and the thread pointer
2266 * will be NULL. Callers should be careful only to pass a
2267 * NULL thread pointer when there really is no owning
2268 * context that might have locks, or the locks will be
2271 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2273 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2274 lf.l_whence = SEEK_SET;
2277 lf.l_type = F_UNLCK;
2278 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2279 F_UNLCK, &lf, F_POSIX);
2281 fdtol = td->td_proc->p_fdtol;
2282 if (fdtol != NULL) {
2284 * Handle special case where file descriptor table is
2285 * shared between multiple process leaders.
2287 fdp = td->td_proc->p_fd;
2288 FILEDESC_XLOCK(fdp);
2289 for (fdtol = fdtol->fdl_next;
2290 fdtol != td->td_proc->p_fdtol;
2291 fdtol = fdtol->fdl_next) {
2292 if ((fdtol->fdl_leader->p_flag &
2295 fdtol->fdl_holdcount++;
2296 FILEDESC_XUNLOCK(fdp);
2297 lf.l_whence = SEEK_SET;
2300 lf.l_type = F_UNLCK;
2302 (void) VOP_ADVLOCK(vp,
2303 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2305 FILEDESC_XLOCK(fdp);
2306 fdtol->fdl_holdcount--;
2307 if (fdtol->fdl_holdcount == 0 &&
2308 fdtol->fdl_wakeup != 0) {
2309 fdtol->fdl_wakeup = 0;
2313 FILEDESC_XUNLOCK(fdp);
2316 return (fdrop(fp, td));
2320 * Initialize the file pointer with the specified properties.
2322 * The ops are set with release semantics to be certain that the flags, type,
2323 * and data are visible when ops is. This is to prevent ops methods from being
2324 * called with bad data.
2327 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2332 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2336 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2337 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2342 cap_rights_t haverights;
2347 * Avoid reads reordering and then a first access to the
2348 * fdp->fd_ofiles table which could result in OOB operation.
2350 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2353 * Fetch the descriptor locklessly. We avoid fdrop() races by
2354 * never raising a refcount above 0. To accomplish this we have
2355 * to use a cmpset loop rather than an atomic_add. The descriptor
2356 * must be re-verified once we acquire a reference to be certain
2357 * that the identity is still correct and we did not lose a race
2358 * due to preemption.
2361 fp = fdp->fd_ofiles[fd].fde_file;
2365 haverights = *cap_rights(fdp, fd);
2366 if (needrightsp != NULL) {
2367 error = cap_check(&haverights, needrightsp);
2370 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2371 error = cap_fcntl_check(fdp, fd, needfcntl);
2377 count = fp->f_count;
2381 * Use an acquire barrier to prevent caching of fd_ofiles
2382 * so it is refreshed for verification.
2384 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2386 if (fp == fdp->fd_ofiles[fd].fde_file)
2388 fdrop(fp, curthread);
2391 if (haverightsp != NULL) {
2393 *haverightsp = haverights;
2395 CAP_ALL(haverightsp);
2402 * Extract the file pointer associated with the specified descriptor for the
2403 * current user process.
2405 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2408 * File's rights will be checked against the capability rights mask.
2410 * If an error occured the non-zero error is returned and *fpp is set to
2411 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2412 * responsible for fdrop().
2415 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2416 cap_rights_t *needrightsp, u_char *maxprotp)
2418 struct filedesc *fdp;
2420 cap_rights_t haverights, needrights;
2424 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2426 if (needrightsp != NULL)
2427 needrights = *needrightsp;
2429 cap_rights_init(&needrights);
2430 if (maxprotp != NULL)
2431 cap_rights_set(&needrights, CAP_MMAP);
2432 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2435 if (fp->f_ops == &badfileops) {
2442 * If requested, convert capability rights to access flags.
2444 if (maxprotp != NULL)
2445 *maxprotp = cap_rights_to_vmprot(&haverights);
2446 #else /* !CAPABILITIES */
2447 if (maxprotp != NULL)
2448 *maxprotp = VM_PROT_ALL;
2449 #endif /* CAPABILITIES */
2452 * FREAD and FWRITE failure return EBADF as per POSIX.
2458 if ((fp->f_flag & flags) == 0)
2462 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2463 ((fp->f_flag & FWRITE) != 0))
2469 KASSERT(0, ("wrong flags"));
2482 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2485 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2489 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2493 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2497 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2500 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2504 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2507 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2511 * Like fget() but loads the underlying vnode, or returns an error if the
2512 * descriptor does not represent a vnode. Note that pipes use vnodes but
2513 * never have VM objects. The returned vnode will be vref()'d.
2515 * XXX: what about the unused flags ?
2518 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2525 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2528 if (fp->f_vnode == NULL) {
2540 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2543 return (_fgetvp(td, fd, 0, rightsp, vpp));
2547 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2548 struct filecaps *havecaps, struct vnode **vpp)
2550 struct filedesc *fdp;
2556 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2559 fp = fget_locked(fdp, fd);
2560 if (fp == NULL || fp->f_ops == &badfileops)
2564 if (needrightsp != NULL) {
2565 error = cap_check(cap_rights(fdp, fd), needrightsp);
2571 if (fp->f_vnode == NULL)
2576 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2582 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2585 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2589 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2592 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2597 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2601 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2606 * Like fget() but loads the underlying socket, or returns an error if the
2607 * descriptor does not represent a socket.
2609 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2612 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2613 * on their file descriptor reference to prevent the socket from being free'd
2617 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2626 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2628 if (fp->f_type != DTYPE_SOCKET) {
2633 *fflagp = fp->f_flag;
2644 * Drop the reference count on the socket and XXX release the SX lock in the
2645 * future. The last reference closes the socket.
2647 * Note: fputsock() is deprecated, see comment for fgetsock().
2650 fputsock(struct socket *so)
2655 CURVNET_SET(so->so_vnet);
2661 * Handle the last reference to a file being closed.
2664 _fdrop(struct file *fp, struct thread *td)
2669 if (fp->f_count != 0)
2670 panic("fdrop: count %d", fp->f_count);
2671 if (fp->f_ops != &badfileops)
2672 error = fo_close(fp, td);
2673 atomic_subtract_int(&openfiles, 1);
2675 free(fp->f_advice, M_FADVISE);
2676 uma_zfree(file_zone, fp);
2682 * Apply an advisory lock on a file descriptor.
2684 * Just attempt to get a record lock of the requested type on the entire file
2685 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2687 #ifndef _SYS_SYSPROTO_H_
2695 sys_flock(struct thread *td, struct flock_args *uap)
2700 cap_rights_t rights;
2703 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2706 if (fp->f_type != DTYPE_VNODE) {
2708 return (EOPNOTSUPP);
2712 lf.l_whence = SEEK_SET;
2715 if (uap->how & LOCK_UN) {
2716 lf.l_type = F_UNLCK;
2717 atomic_clear_int(&fp->f_flag, FHASLOCK);
2718 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2721 if (uap->how & LOCK_EX)
2722 lf.l_type = F_WRLCK;
2723 else if (uap->how & LOCK_SH)
2724 lf.l_type = F_RDLCK;
2729 atomic_set_int(&fp->f_flag, FHASLOCK);
2730 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2731 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2737 * Duplicate the specified descriptor to a free descriptor.
2740 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2741 int openerror, int *indxp)
2746 KASSERT(openerror == ENODEV || openerror == ENXIO,
2747 ("unexpected error %d in %s", openerror, __func__));
2750 * If the to-be-dup'd fd number is greater than the allowed number
2751 * of file descriptors, or the fd to be dup'd has already been
2752 * closed, then reject.
2754 FILEDESC_XLOCK(fdp);
2755 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2756 FILEDESC_XUNLOCK(fdp);
2760 error = fdalloc(td, 0, &indx);
2762 FILEDESC_XUNLOCK(fdp);
2767 * There are two cases of interest here.
2769 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2771 * For ENXIO steal away the file structure from (dfd) and store it in
2772 * (indx). (dfd) is effectively closed by this operation.
2774 switch (openerror) {
2777 * Check that the mode the file is being opened for is a
2778 * subset of the mode of the existing descriptor.
2780 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2781 fdunused(fdp, indx);
2782 FILEDESC_XUNLOCK(fdp);
2786 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2787 filecaps_copy(&fdp->fd_ofiles[dfd].fde_caps,
2788 &fdp->fd_ofiles[indx].fde_caps);
2792 * Steal away the file pointer from dfd and stuff it into indx.
2794 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2795 bzero(&fdp->fd_ofiles[dfd], sizeof(fdp->fd_ofiles[dfd]));
2799 FILEDESC_XUNLOCK(fdp);
2805 * Scan all active processes and prisons to see if any of them have a current
2806 * or root directory of `olddp'. If so, replace them with the new mount point.
2809 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2811 struct filedesc *fdp;
2816 if (vrefcnt(olddp) == 1)
2819 sx_slock(&allproc_lock);
2820 FOREACH_PROC_IN_SYSTEM(p) {
2824 FILEDESC_XLOCK(fdp);
2825 if (fdp->fd_cdir == olddp) {
2827 fdp->fd_cdir = newdp;
2830 if (fdp->fd_rdir == olddp) {
2832 fdp->fd_rdir = newdp;
2835 if (fdp->fd_jdir == olddp) {
2837 fdp->fd_jdir = newdp;
2840 FILEDESC_XUNLOCK(fdp);
2843 sx_sunlock(&allproc_lock);
2844 if (rootvnode == olddp) {
2849 mtx_lock(&prison0.pr_mtx);
2850 if (prison0.pr_root == olddp) {
2852 prison0.pr_root = newdp;
2855 mtx_unlock(&prison0.pr_mtx);
2856 sx_slock(&allprison_lock);
2857 TAILQ_FOREACH(pr, &allprison, pr_list) {
2858 mtx_lock(&pr->pr_mtx);
2859 if (pr->pr_root == olddp) {
2861 pr->pr_root = newdp;
2864 mtx_unlock(&pr->pr_mtx);
2866 sx_sunlock(&allprison_lock);
2871 struct filedesc_to_leader *
2872 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2874 struct filedesc_to_leader *fdtol;
2876 fdtol = malloc(sizeof(struct filedesc_to_leader),
2877 M_FILEDESC_TO_LEADER,
2879 fdtol->fdl_refcount = 1;
2880 fdtol->fdl_holdcount = 0;
2881 fdtol->fdl_wakeup = 0;
2882 fdtol->fdl_leader = leader;
2884 FILEDESC_XLOCK(fdp);
2885 fdtol->fdl_next = old->fdl_next;
2886 fdtol->fdl_prev = old;
2887 old->fdl_next = fdtol;
2888 fdtol->fdl_next->fdl_prev = fdtol;
2889 FILEDESC_XUNLOCK(fdp);
2891 fdtol->fdl_next = fdtol;
2892 fdtol->fdl_prev = fdtol;
2898 * Get file structures globally.
2901 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2904 struct filedesc *fdp;
2909 error = sysctl_wire_old_buffer(req, 0);
2912 if (req->oldptr == NULL) {
2914 sx_slock(&allproc_lock);
2915 FOREACH_PROC_IN_SYSTEM(p) {
2916 if (p->p_state == PRS_NEW)
2921 /* overestimates sparse tables. */
2922 if (fdp->fd_lastfile > 0)
2923 n += fdp->fd_lastfile;
2926 sx_sunlock(&allproc_lock);
2927 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2930 bzero(&xf, sizeof(xf));
2931 xf.xf_size = sizeof(xf);
2932 sx_slock(&allproc_lock);
2933 FOREACH_PROC_IN_SYSTEM(p) {
2935 if (p->p_state == PRS_NEW) {
2939 if (p_cansee(req->td, p) != 0) {
2943 xf.xf_pid = p->p_pid;
2944 xf.xf_uid = p->p_ucred->cr_uid;
2949 FILEDESC_SLOCK(fdp);
2950 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
2951 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
2955 xf.xf_data = fp->f_data;
2956 xf.xf_vnode = fp->f_vnode;
2957 xf.xf_type = fp->f_type;
2958 xf.xf_count = fp->f_count;
2960 xf.xf_offset = foffset_get(fp);
2961 xf.xf_flag = fp->f_flag;
2962 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2966 FILEDESC_SUNLOCK(fdp);
2971 sx_sunlock(&allproc_lock);
2975 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
2976 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2978 #ifdef KINFO_OFILE_SIZE
2979 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2982 #ifdef COMPAT_FREEBSD7
2984 export_vnode_for_osysctl(struct vnode *vp, int type,
2985 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2988 char *fullpath, *freepath;
2990 bzero(kif, sizeof(*kif));
2991 kif->kf_structsize = sizeof(*kif);
2995 kif->kf_type = KF_TYPE_VNODE;
2996 /* This function only handles directories. */
2997 if (vp->v_type != VDIR) {
3001 kif->kf_vnode_type = KF_VTYPE_VDIR;
3004 * This is not a true file descriptor, so we set a bogus refcount
3005 * and offset to indicate these fields should be ignored.
3007 kif->kf_ref_count = -1;
3008 kif->kf_offset = -1;
3012 FILEDESC_SUNLOCK(fdp);
3013 vn_fullpath(curthread, vp, &fullpath, &freepath);
3015 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3016 if (freepath != NULL)
3017 free(freepath, M_TEMP);
3018 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3019 FILEDESC_SLOCK(fdp);
3024 * Get per-process file descriptors for use by procstat(1), et al.
3027 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3029 char *fullpath, *freepath;
3030 struct kinfo_ofile *kif;
3031 struct filedesc *fdp;
3032 int error, i, *name;
3033 struct shmfd *shmfd;
3042 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3049 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3050 FILEDESC_SLOCK(fdp);
3051 if (fdp->fd_cdir != NULL)
3052 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3054 if (fdp->fd_rdir != NULL)
3055 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3057 if (fdp->fd_jdir != NULL)
3058 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3060 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3061 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3063 bzero(kif, sizeof(*kif));
3064 kif->kf_structsize = sizeof(*kif);
3072 switch (fp->f_type) {
3074 kif->kf_type = KF_TYPE_VNODE;
3079 kif->kf_type = KF_TYPE_SOCKET;
3084 kif->kf_type = KF_TYPE_PIPE;
3088 kif->kf_type = KF_TYPE_FIFO;
3093 kif->kf_type = KF_TYPE_KQUEUE;
3097 kif->kf_type = KF_TYPE_CRYPTO;
3101 kif->kf_type = KF_TYPE_MQUEUE;
3105 kif->kf_type = KF_TYPE_SHM;
3110 kif->kf_type = KF_TYPE_SEM;
3115 kif->kf_type = KF_TYPE_PTS;
3120 case DTYPE_PROCDESC:
3121 kif->kf_type = KF_TYPE_PROCDESC;
3126 kif->kf_type = KF_TYPE_UNKNOWN;
3129 kif->kf_ref_count = fp->f_count;
3130 if (fp->f_flag & FREAD)
3131 kif->kf_flags |= KF_FLAG_READ;
3132 if (fp->f_flag & FWRITE)
3133 kif->kf_flags |= KF_FLAG_WRITE;
3134 if (fp->f_flag & FAPPEND)
3135 kif->kf_flags |= KF_FLAG_APPEND;
3136 if (fp->f_flag & FASYNC)
3137 kif->kf_flags |= KF_FLAG_ASYNC;
3138 if (fp->f_flag & FFSYNC)
3139 kif->kf_flags |= KF_FLAG_FSYNC;
3140 if (fp->f_flag & FNONBLOCK)
3141 kif->kf_flags |= KF_FLAG_NONBLOCK;
3142 if (fp->f_flag & O_DIRECT)
3143 kif->kf_flags |= KF_FLAG_DIRECT;
3144 if (fp->f_flag & FHASLOCK)
3145 kif->kf_flags |= KF_FLAG_HASLOCK;
3146 kif->kf_offset = foffset_get(fp);
3149 switch (vp->v_type) {
3151 kif->kf_vnode_type = KF_VTYPE_VNON;
3154 kif->kf_vnode_type = KF_VTYPE_VREG;
3157 kif->kf_vnode_type = KF_VTYPE_VDIR;
3160 kif->kf_vnode_type = KF_VTYPE_VBLK;
3163 kif->kf_vnode_type = KF_VTYPE_VCHR;
3166 kif->kf_vnode_type = KF_VTYPE_VLNK;
3169 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3172 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3175 kif->kf_vnode_type = KF_VTYPE_VBAD;
3178 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3182 * It is OK to drop the filedesc lock here as we will
3183 * re-validate and re-evaluate its properties when
3184 * the loop continues.
3188 FILEDESC_SUNLOCK(fdp);
3189 vn_fullpath(curthread, vp, &fullpath, &freepath);
3191 strlcpy(kif->kf_path, fullpath,
3192 sizeof(kif->kf_path));
3193 if (freepath != NULL)
3194 free(freepath, M_TEMP);
3195 FILEDESC_SLOCK(fdp);
3198 struct sockaddr *sa;
3200 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3201 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3202 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3205 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3206 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3207 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3210 kif->kf_sock_domain =
3211 so->so_proto->pr_domain->dom_family;
3212 kif->kf_sock_type = so->so_type;
3213 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3216 strlcpy(kif->kf_path, tty_devname(tp),
3217 sizeof(kif->kf_path));
3220 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3221 if (ks != NULL && ksem_info != NULL)
3222 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3223 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3227 FILEDESC_SUNLOCK(fdp);
3233 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3234 CTLFLAG_RD||CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3235 "Process ofiledesc entries");
3236 #endif /* COMPAT_FREEBSD7 */
3238 #ifdef KINFO_FILE_SIZE
3239 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3242 struct export_fd_buf {
3243 struct filedesc *fdp;
3246 struct kinfo_file kif;
3250 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3251 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3256 } fflags_table[] = {
3257 { FAPPEND, KF_FLAG_APPEND },
3258 { FASYNC, KF_FLAG_ASYNC },
3259 { FFSYNC, KF_FLAG_FSYNC },
3260 { FHASLOCK, KF_FLAG_HASLOCK },
3261 { FNONBLOCK, KF_FLAG_NONBLOCK },
3262 { FREAD, KF_FLAG_READ },
3263 { FWRITE, KF_FLAG_WRITE },
3264 { O_CREAT, KF_FLAG_CREAT },
3265 { O_DIRECT, KF_FLAG_DIRECT },
3266 { O_EXCL, KF_FLAG_EXCL },
3267 { O_EXEC, KF_FLAG_EXEC },
3268 { O_EXLOCK, KF_FLAG_EXLOCK },
3269 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3270 { O_SHLOCK, KF_FLAG_SHLOCK },
3271 { O_TRUNC, KF_FLAG_TRUNC }
3273 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3274 struct kinfo_file *kif;
3279 if (efbuf->remainder == 0)
3282 bzero(kif, sizeof(*kif));
3283 locked = efbuf->fdp != NULL;
3288 FILEDESC_SUNLOCK(efbuf->fdp);
3291 vp = (struct vnode *)data;
3292 error = fill_vnode_info(vp, kif);
3295 case KF_TYPE_SOCKET:
3296 error = fill_socket_info((struct socket *)data, kif);
3299 error = fill_pipe_info((struct pipe *)data, kif);
3302 error = fill_pts_info((struct tty *)data, kif);
3304 case KF_TYPE_PROCDESC:
3305 error = fill_procdesc_info((struct procdesc *)data, kif);
3308 error = fill_sem_info((struct file *)data, kif);
3311 error = fill_shm_info((struct file *)data, kif);
3317 kif->kf_status |= KF_ATTR_VALID;
3320 * Translate file access flags.
3322 for (i = 0; i < NFFLAGS; i++)
3323 if (fflags & fflags_table[i].fflag)
3324 kif->kf_flags |= fflags_table[i].kf_fflag;
3325 if (rightsp != NULL)
3326 kif->kf_cap_rights = *rightsp;
3328 cap_rights_init(&kif->kf_cap_rights);
3330 kif->kf_type = type;
3331 kif->kf_ref_count = refcnt;
3332 kif->kf_offset = offset;
3333 /* Pack record size down */
3334 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3335 strlen(kif->kf_path) + 1;
3336 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3337 if (efbuf->remainder != -1) {
3338 if (efbuf->remainder < kif->kf_structsize) {
3339 /* Terminate export. */
3340 efbuf->remainder = 0;
3341 if (efbuf->fdp != NULL && !locked)
3342 FILEDESC_SLOCK(efbuf->fdp);
3345 efbuf->remainder -= kif->kf_structsize;
3348 FILEDESC_SUNLOCK(efbuf->fdp);
3349 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3350 if (efbuf->fdp != NULL)
3351 FILEDESC_SLOCK(efbuf->fdp);
3356 * Store a process file descriptor information to sbuf.
3358 * Takes a locked proc as argument, and returns with the proc unlocked.
3361 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3364 struct filedesc *fdp;
3365 struct export_fd_buf *efbuf;
3366 struct vnode *cttyvp, *textvp, *tracevp;
3370 int type, refcnt, fflags;
3371 cap_rights_t rights;
3373 PROC_LOCK_ASSERT(p, MA_OWNED);
3376 tracevp = p->p_tracevp;
3377 if (tracevp != NULL)
3380 textvp = p->p_textvp;
3383 /* Controlling tty. */
3385 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3386 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3392 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3395 efbuf->remainder = maxlen;
3396 if (tracevp != NULL)
3397 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3398 FREAD | FWRITE, -1, -1, NULL, efbuf);
3400 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3401 FREAD, -1, -1, NULL, efbuf);
3403 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3404 FREAD | FWRITE, -1, -1, NULL, efbuf);
3409 FILEDESC_SLOCK(fdp);
3410 /* working directory */
3411 if (fdp->fd_cdir != NULL) {
3413 data = fdp->fd_cdir;
3414 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3415 FREAD, -1, -1, NULL, efbuf);
3417 /* root directory */
3418 if (fdp->fd_rdir != NULL) {
3420 data = fdp->fd_rdir;
3421 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3422 FREAD, -1, -1, NULL, efbuf);
3424 /* jail directory */
3425 if (fdp->fd_jdir != NULL) {
3427 data = fdp->fd_jdir;
3428 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3429 FREAD, -1, -1, NULL, efbuf);
3431 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3432 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3436 rights = *cap_rights(fdp, i);
3437 #else /* !CAPABILITIES */
3438 cap_rights_init(&rights);
3440 switch (fp->f_type) {
3442 type = KF_TYPE_VNODE;
3448 type = KF_TYPE_SOCKET;
3453 type = KF_TYPE_PIPE;
3458 type = KF_TYPE_FIFO;
3464 type = KF_TYPE_KQUEUE;
3468 type = KF_TYPE_CRYPTO;
3472 type = KF_TYPE_MQUEUE;
3491 case DTYPE_PROCDESC:
3492 type = KF_TYPE_PROCDESC;
3498 type = KF_TYPE_UNKNOWN;
3501 refcnt = fp->f_count;
3502 fflags = fp->f_flag;
3503 offset = foffset_get(fp);
3506 * Create sysctl entry.
3507 * It is OK to drop the filedesc lock here as we will
3508 * re-validate and re-evaluate its properties when
3509 * the loop continues.
3511 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3512 offset, &rights, efbuf);
3516 FILEDESC_SUNLOCK(fdp);
3519 free(efbuf, M_TEMP);
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 | PGET_NOTWEXIT, &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;
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 vn_lock(vp, LK_SHARED | LK_RETRY);
3608 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3612 if (va.va_fsid != VNOVAL)
3613 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3615 kif->kf_un.kf_file.kf_file_fsid =
3616 vp->v_mount->mnt_stat.f_fsid.val[0];
3617 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3618 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3619 kif->kf_un.kf_file.kf_file_size = va.va_size;
3620 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3625 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3627 struct sockaddr *sa;
3628 struct inpcb *inpcb;
3629 struct unpcb *unpcb;
3634 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3635 kif->kf_sock_type = so->so_type;
3636 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3637 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3638 switch(kif->kf_sock_domain) {
3641 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3642 if (so->so_pcb != NULL) {
3643 inpcb = (struct inpcb *)(so->so_pcb);
3644 kif->kf_un.kf_sock.kf_sock_inpcb =
3645 (uintptr_t)inpcb->inp_ppcb;
3650 if (so->so_pcb != NULL) {
3651 unpcb = (struct unpcb *)(so->so_pcb);
3652 if (unpcb->unp_conn) {
3653 kif->kf_un.kf_sock.kf_sock_unpconn =
3654 (uintptr_t)unpcb->unp_conn;
3655 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3656 so->so_rcv.sb_state;
3657 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3658 so->so_snd.sb_state;
3663 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3664 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3665 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3668 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3669 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3670 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3673 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3674 sizeof(kif->kf_path));
3679 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3684 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3685 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3690 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3695 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3696 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3697 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3702 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3707 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3712 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3718 if (fp->f_data == NULL)
3720 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3722 if (ksem_info == NULL)
3724 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3725 &kif->kf_un.kf_sem.kf_sem_value);
3726 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3731 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3737 if (fp->f_data == NULL)
3739 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3741 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3742 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3743 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3747 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3748 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3749 "Process filedesc entries");
3753 * For the purposes of debugging, generate a human-readable string for the
3757 file_type_to_name(short type)
3787 * For the purposes of debugging, identify a process (if any, perhaps one of
3788 * many) that references the passed file in its file descriptor array. Return
3791 static struct proc *
3792 file_to_first_proc(struct file *fp)
3794 struct filedesc *fdp;
3798 FOREACH_PROC_IN_SYSTEM(p) {
3799 if (p->p_state == PRS_NEW)
3804 for (n = 0; n <= fdp->fd_lastfile; n++) {
3805 if (fp == fdp->fd_ofiles[n].fde_file)
3813 db_print_file(struct file *fp, int header)
3818 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3819 "File", "Type", "Data", "Flag", "GCFl", "Count",
3820 "MCount", "Vnode", "FPID", "FCmd");
3821 p = file_to_first_proc(fp);
3822 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3823 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3824 0, fp->f_count, 0, fp->f_vnode,
3825 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3828 DB_SHOW_COMMAND(file, db_show_file)
3833 db_printf("usage: show file <addr>\n");
3836 fp = (struct file *)addr;
3837 db_print_file(fp, 1);
3840 DB_SHOW_COMMAND(files, db_show_files)
3842 struct filedesc *fdp;
3849 FOREACH_PROC_IN_SYSTEM(p) {
3850 if (p->p_state == PRS_NEW)
3852 if ((fdp = p->p_fd) == NULL)
3854 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3855 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3857 db_print_file(fp, header);
3864 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3865 &maxfilesperproc, 0, "Maximum files allowed open per process");
3867 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3868 &maxfiles, 0, "Maximum number of files");
3870 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3871 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3875 filelistinit(void *dummy)
3878 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3879 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3880 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3881 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3883 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3885 /*-------------------------------------------------------------------*/
3888 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3889 int flags, struct thread *td)
3896 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3904 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3912 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3920 badfo_kqfilter(struct file *fp, struct knote *kn)
3927 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3935 badfo_close(struct file *fp, struct thread *td)
3942 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3950 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3958 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3959 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3960 int kflags, struct thread *td)
3966 struct fileops badfileops = {
3967 .fo_read = badfo_readwrite,
3968 .fo_write = badfo_readwrite,
3969 .fo_truncate = badfo_truncate,
3970 .fo_ioctl = badfo_ioctl,
3971 .fo_poll = badfo_poll,
3972 .fo_kqfilter = badfo_kqfilter,
3973 .fo_stat = badfo_stat,
3974 .fo_close = badfo_close,
3975 .fo_chmod = badfo_chmod,
3976 .fo_chown = badfo_chown,
3977 .fo_sendfile = badfo_sendfile,
3981 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3989 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3997 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3998 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3999 int kflags, struct thread *td)
4005 /*-------------------------------------------------------------------*/
4008 * File Descriptor pseudo-device driver (/dev/fd/).
4010 * Opening minor device N dup()s the file (if any) connected to file
4011 * descriptor N belonging to the calling process. Note that this driver
4012 * consists of only the ``open()'' routine, because all subsequent
4013 * references to this file will be direct to the other driver.
4015 * XXX: we could give this one a cloning event handler if necessary.
4020 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4024 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4025 * the file descriptor being sought for duplication. The error
4026 * return ensures that the vnode for this device will be released
4027 * by vn_open. Open will detect this special error and take the
4028 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4029 * will simply report the error.
4031 td->td_dupfd = dev2unit(dev);
4035 static struct cdevsw fildesc_cdevsw = {
4036 .d_version = D_VERSION,
4042 fildesc_drvinit(void *unused)
4046 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4047 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4048 make_dev_alias(dev, "stdin");
4049 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4050 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4051 make_dev_alias(dev, "stdout");
4052 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4053 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4054 make_dev_alias(dev, "stderr");
4057 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);