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.
300 fdfree(struct filedesc *fdp, int fd)
302 struct filedescent *fde;
304 fde = &fdp->fd_ofiles[fd];
305 filecaps_free(&fde->fde_caps);
306 bzero(fde, sizeof(*fde));
311 * System calls on descriptors.
313 #ifndef _SYS_SYSPROTO_H_
314 struct getdtablesize_args {
320 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
322 struct proc *p = td->td_proc;
327 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
328 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
330 if (lim < td->td_retval[0])
331 td->td_retval[0] = lim;
336 * Duplicate a file descriptor to a particular value.
338 * Note: keep in mind that a potential race condition exists when closing
339 * descriptors from a shared descriptor table (via rfork).
341 #ifndef _SYS_SYSPROTO_H_
349 sys_dup2(struct thread *td, struct dup2_args *uap)
352 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
357 * Duplicate a file descriptor.
359 #ifndef _SYS_SYSPROTO_H_
366 sys_dup(struct thread *td, struct dup_args *uap)
369 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
373 * The file control system call.
375 #ifndef _SYS_SYSPROTO_H_
384 sys_fcntl(struct thread *td, struct fcntl_args *uap)
399 * Convert old flock structure to new.
401 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
402 fl.l_start = ofl.l_start;
403 fl.l_len = ofl.l_len;
404 fl.l_pid = ofl.l_pid;
405 fl.l_type = ofl.l_type;
406 fl.l_whence = ofl.l_whence;
426 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
435 error = kern_fcntl(td, uap->fd, cmd, arg);
438 if (uap->cmd == F_OGETLK) {
439 ofl.l_start = fl.l_start;
440 ofl.l_len = fl.l_len;
441 ofl.l_pid = fl.l_pid;
442 ofl.l_type = fl.l_type;
443 ofl.l_whence = fl.l_whence;
444 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
445 } else if (uap->cmd == F_GETLK) {
446 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
452 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
454 struct filedesc *fdp;
456 struct file *fp, *fp2;
457 struct filedescent *fde;
474 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
477 case F_DUPFD_CLOEXEC:
479 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
485 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
488 case F_DUP2FD_CLOEXEC:
490 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
496 if ((fp = fget_locked(fdp, fd)) == NULL) {
497 FILEDESC_SUNLOCK(fdp);
501 fde = &fdp->fd_ofiles[fd];
503 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
504 FILEDESC_SUNLOCK(fdp);
509 if ((fp = fget_locked(fdp, fd)) == NULL) {
510 FILEDESC_XUNLOCK(fdp);
514 fde = &fdp->fd_ofiles[fd];
515 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
516 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
517 FILEDESC_XUNLOCK(fdp);
521 error = fget_unlocked(fdp, fd,
522 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
525 td->td_retval[0] = OFLAGS(fp->f_flag);
530 error = fget_unlocked(fdp, fd,
531 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
535 tmp = flg = fp->f_flag;
537 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
538 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
539 tmp = fp->f_flag & FNONBLOCK;
540 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
545 tmp = fp->f_flag & FASYNC;
546 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
551 atomic_clear_int(&fp->f_flag, FNONBLOCK);
553 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
558 error = fget_unlocked(fdp, fd,
559 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
562 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
564 td->td_retval[0] = tmp;
569 error = fget_unlocked(fdp, fd,
570 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
574 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
579 error = priv_check(td, PRIV_NFS_LOCKD);
587 /* FALLTHROUGH F_SETLK */
591 cap_rights_init(&rights, CAP_FLOCK);
592 error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
595 if (fp->f_type != DTYPE_VNODE) {
601 flp = (struct flock *)arg;
602 if (flp->l_whence == SEEK_CUR) {
603 foffset = foffset_get(fp);
606 foffset > OFF_MAX - flp->l_start)) {
607 FILEDESC_SUNLOCK(fdp);
612 flp->l_start += foffset;
616 switch (flp->l_type) {
618 if ((fp->f_flag & FREAD) == 0) {
622 PROC_LOCK(p->p_leader);
623 p->p_leader->p_flag |= P_ADVLOCK;
624 PROC_UNLOCK(p->p_leader);
625 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
629 if ((fp->f_flag & FWRITE) == 0) {
633 PROC_LOCK(p->p_leader);
634 p->p_leader->p_flag |= P_ADVLOCK;
635 PROC_UNLOCK(p->p_leader);
636 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
640 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
645 * Temporary api for testing remote lock
648 if (flg != F_REMOTE) {
652 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
653 F_UNLCKSYS, flp, flg);
659 if (error != 0 || flp->l_type == F_UNLCK ||
660 flp->l_type == F_UNLCKSYS) {
666 * Check for a race with close.
668 * The vnode is now advisory locked (or unlocked, but this case
669 * is not really important) as the caller requested.
670 * We had to drop the filedesc lock, so we need to recheck if
671 * the descriptor is still valid, because if it was closed
672 * in the meantime we need to remove advisory lock from the
673 * vnode - close on any descriptor leading to an advisory
674 * locked vnode, removes that lock.
675 * We will return 0 on purpose in that case, as the result of
676 * successful advisory lock might have been externally visible
677 * already. This is fine - effectively we pretend to the caller
678 * that the closing thread was a bit slower and that the
679 * advisory lock succeeded before the close.
681 error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
687 flp->l_whence = SEEK_SET;
690 flp->l_type = F_UNLCK;
691 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
692 F_UNLCK, flp, F_POSIX);
699 error = fget_unlocked(fdp, fd,
700 cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
703 if (fp->f_type != DTYPE_VNODE) {
708 flp = (struct flock *)arg;
709 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
710 flp->l_type != F_UNLCK) {
715 if (flp->l_whence == SEEK_CUR) {
716 foffset = foffset_get(fp);
717 if ((flp->l_start > 0 &&
718 foffset > OFF_MAX - flp->l_start) ||
720 foffset < OFF_MIN - flp->l_start)) {
721 FILEDESC_SUNLOCK(fdp);
726 flp->l_start += foffset;
729 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
735 arg = arg ? 128 * 1024: 0;
738 error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
741 if (fp->f_type != DTYPE_VNODE) {
748 error = vn_lock(vp, LK_SHARED);
753 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
755 fp->f_seqcount = (arg + bsize - 1) / bsize;
757 new = old = fp->f_flag;
759 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
762 new = old = fp->f_flag;
764 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
777 getmaxfd(struct proc *p)
782 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
789 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
792 do_dup(struct thread *td, int flags, int old, int new,
795 struct filedesc *fdp;
796 struct filedescent *oldfde, *newfde;
806 * Verify we have a valid descriptor to dup from and possibly to
807 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
808 * return EINVAL when the new descriptor is out of bounds.
813 return (flags & DUP_FCNTL ? EINVAL : EBADF);
816 return (flags & DUP_FCNTL ? EINVAL : EBADF);
819 if (fget_locked(fdp, old) == NULL) {
820 FILEDESC_XUNLOCK(fdp);
823 oldfde = &fdp->fd_ofiles[old];
824 if (flags & DUP_FIXED && old == new) {
826 if (flags & DUP_CLOEXEC)
827 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
828 FILEDESC_XUNLOCK(fdp);
831 fp = oldfde->fde_file;
835 * If the caller specified a file descriptor, make sure the file
836 * table is large enough to hold it, and grab it. Otherwise, just
837 * allocate a new descriptor the usual way.
839 if (flags & DUP_FIXED) {
840 if (new >= fdp->fd_nfiles) {
842 * The resource limits are here instead of e.g.
843 * fdalloc(), because the file descriptor table may be
844 * shared between processes, so we can't really use
845 * racct_add()/racct_sub(). Instead of counting the
846 * number of actually allocated descriptors, just put
847 * the limit on the size of the file descriptor table.
851 error = racct_set(p, RACCT_NOFILE, new + 1);
854 FILEDESC_XUNLOCK(fdp);
859 fdgrowtable_exp(fdp, new + 1);
860 oldfde = &fdp->fd_ofiles[old];
862 newfde = &fdp->fd_ofiles[new];
863 if (newfde->fde_file == NULL)
866 if ((error = fdalloc(td, new, &new)) != 0) {
867 FILEDESC_XUNLOCK(fdp);
871 newfde = &fdp->fd_ofiles[new];
874 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
875 KASSERT(old != new, ("new fd is same as old"));
877 delfp = newfde->fde_file;
880 * Duplicate the source descriptor.
883 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
884 if ((flags & DUP_CLOEXEC) != 0)
885 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
887 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
888 if (new > fdp->fd_lastfile)
889 fdp->fd_lastfile = new;
893 (void) closefp(fdp, new, delfp, td, 1);
894 /* closefp() drops the FILEDESC lock for us. */
896 FILEDESC_XUNLOCK(fdp);
903 * If sigio is on the list associated with a process or process group,
904 * disable signalling from the device, remove sigio from the list and
908 funsetown(struct sigio **sigiop)
918 *(sigio->sio_myref) = NULL;
919 if ((sigio)->sio_pgid < 0) {
920 struct pgrp *pg = (sigio)->sio_pgrp;
922 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
926 struct proc *p = (sigio)->sio_proc;
928 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
933 crfree(sigio->sio_ucred);
934 free(sigio, M_SIGIO);
938 * Free a list of sigio structures.
939 * We only need to lock the SIGIO_LOCK because we have made ourselves
940 * inaccessible to callers of fsetown and therefore do not need to lock
941 * the proc or pgrp struct for the list manipulation.
944 funsetownlst(struct sigiolst *sigiolst)
950 sigio = SLIST_FIRST(sigiolst);
957 * Every entry of the list should belong
958 * to a single proc or pgrp.
960 if (sigio->sio_pgid < 0) {
961 pg = sigio->sio_pgrp;
962 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
963 } else /* if (sigio->sio_pgid > 0) */ {
965 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
969 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
970 *(sigio->sio_myref) = NULL;
972 KASSERT(sigio->sio_pgid < 0,
973 ("Proc sigio in pgrp sigio list"));
974 KASSERT(sigio->sio_pgrp == pg,
975 ("Bogus pgrp in sigio list"));
977 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
980 } else /* if (p != NULL) */ {
981 KASSERT(sigio->sio_pgid > 0,
982 ("Pgrp sigio in proc sigio list"));
983 KASSERT(sigio->sio_proc == p,
984 ("Bogus proc in sigio list"));
986 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
991 crfree(sigio->sio_ucred);
992 free(sigio, M_SIGIO);
999 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1001 * After permission checking, add a sigio structure to the sigio list for
1002 * the process or process group.
1005 fsetown(pid_t pgid, struct sigio **sigiop)
1009 struct sigio *sigio;
1019 /* Allocate and fill in the new sigio out of locks. */
1020 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1021 sigio->sio_pgid = pgid;
1022 sigio->sio_ucred = crhold(curthread->td_ucred);
1023 sigio->sio_myref = sigiop;
1025 sx_slock(&proctree_lock);
1034 * Policy - Don't allow a process to FSETOWN a process
1035 * in another session.
1037 * Remove this test to allow maximum flexibility or
1038 * restrict FSETOWN to the current process or process
1039 * group for maximum safety.
1042 if (proc->p_session != curthread->td_proc->p_session) {
1048 } else /* if (pgid < 0) */ {
1049 pgrp = pgfind(-pgid);
1057 * Policy - Don't allow a process to FSETOWN a process
1058 * in another session.
1060 * Remove this test to allow maximum flexibility or
1061 * restrict FSETOWN to the current process or process
1062 * group for maximum safety.
1064 if (pgrp->pg_session != curthread->td_proc->p_session) {
1075 * Since funsetownlst() is called without the proctree
1076 * locked, we need to check for P_WEXIT.
1077 * XXX: is ESRCH correct?
1079 if ((proc->p_flag & P_WEXIT) != 0) {
1084 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1085 sigio->sio_proc = proc;
1089 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1090 sigio->sio_pgrp = pgrp;
1093 sx_sunlock(&proctree_lock);
1100 sx_sunlock(&proctree_lock);
1101 crfree(sigio->sio_ucred);
1102 free(sigio, M_SIGIO);
1107 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1111 struct sigio **sigiop;
1116 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1122 * Function drops the filedesc lock on return.
1125 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1130 FILEDESC_XLOCK_ASSERT(fdp);
1133 if (td->td_proc->p_fdtol != NULL) {
1135 * Ask fdfree() to sleep to ensure that all relevant
1136 * process leaders can be traversed in closef().
1138 fdp->fd_holdleaderscount++;
1145 * We now hold the fp reference that used to be owned by the
1146 * descriptor array. We have to unlock the FILEDESC *AFTER*
1147 * knote_fdclose to prevent a race of the fd getting opened, a knote
1148 * added, and deleteing a knote for the new fd.
1150 knote_fdclose(td, fd);
1153 * We need to notify mqueue if the object is of type mqueue.
1155 if (fp->f_type == DTYPE_MQUEUE)
1156 mq_fdclose(td, fd, fp);
1157 FILEDESC_XUNLOCK(fdp);
1159 error = closef(fp, td);
1161 FILEDESC_XLOCK(fdp);
1162 fdp->fd_holdleaderscount--;
1163 if (fdp->fd_holdleaderscount == 0 &&
1164 fdp->fd_holdleaderswakeup != 0) {
1165 fdp->fd_holdleaderswakeup = 0;
1166 wakeup(&fdp->fd_holdleaderscount);
1168 FILEDESC_XUNLOCK(fdp);
1174 * Close a file descriptor.
1176 #ifndef _SYS_SYSPROTO_H_
1185 struct close_args *uap;
1188 return (kern_close(td, uap->fd));
1196 struct filedesc *fdp;
1199 fdp = td->td_proc->p_fd;
1201 AUDIT_SYSCLOSE(td, fd);
1203 FILEDESC_XLOCK(fdp);
1204 if ((fp = fget_locked(fdp, fd)) == NULL) {
1205 FILEDESC_XUNLOCK(fdp);
1210 /* closefp() drops the FILEDESC lock for us. */
1211 return (closefp(fdp, fd, fp, td, 1));
1215 * Close open file descriptors.
1217 #ifndef _SYS_SYSPROTO_H_
1218 struct closefrom_args {
1224 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1226 struct filedesc *fdp;
1229 fdp = td->td_proc->p_fd;
1230 AUDIT_ARG_FD(uap->lowfd);
1233 * Treat negative starting file descriptor values identical to
1234 * closefrom(0) which closes all files.
1238 FILEDESC_SLOCK(fdp);
1239 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1240 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1241 FILEDESC_SUNLOCK(fdp);
1242 (void)kern_close(td, fd);
1243 FILEDESC_SLOCK(fdp);
1246 FILEDESC_SUNLOCK(fdp);
1250 #if defined(COMPAT_43)
1252 * Return status information about a file descriptor.
1254 #ifndef _SYS_SYSPROTO_H_
1255 struct ofstat_args {
1262 ofstat(struct thread *td, struct ofstat_args *uap)
1268 error = kern_fstat(td, uap->fd, &ub);
1271 error = copyout(&oub, uap->sb, sizeof(oub));
1275 #endif /* COMPAT_43 */
1278 * Return status information about a file descriptor.
1280 #ifndef _SYS_SYSPROTO_H_
1288 sys_fstat(struct thread *td, struct fstat_args *uap)
1293 error = kern_fstat(td, uap->fd, &ub);
1295 error = copyout(&ub, uap->sb, sizeof(ub));
1300 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1303 cap_rights_t rights;
1308 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1312 AUDIT_ARG_FILE(td->td_proc, fp);
1314 error = fo_stat(fp, sbp, td->td_ucred, td);
1317 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1324 * Return status information about a file descriptor.
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct nfstat_args {
1334 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1340 error = kern_fstat(td, uap->fd, &ub);
1342 cvtnstat(&ub, &nub);
1343 error = copyout(&nub, uap->sb, sizeof(nub));
1349 * Return pathconf information about a file descriptor.
1351 #ifndef _SYS_SYSPROTO_H_
1352 struct fpathconf_args {
1359 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1363 cap_rights_t rights;
1366 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1370 /* If asynchronous I/O is available, it works for all descriptors. */
1371 if (uap->name == _PC_ASYNC_IO) {
1372 td->td_retval[0] = async_io_version;
1377 vn_lock(vp, LK_SHARED | LK_RETRY);
1378 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1380 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1381 if (uap->name != _PC_PIPE_BUF) {
1384 td->td_retval[0] = PIPE_BUF;
1396 * Initialize filecaps structure.
1399 filecaps_init(struct filecaps *fcaps)
1402 bzero(fcaps, sizeof(*fcaps));
1403 fcaps->fc_nioctls = -1;
1407 * Copy filecaps structure allocating memory for ioctls array if needed.
1410 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1415 if (src->fc_ioctls != NULL) {
1416 KASSERT(src->fc_nioctls > 0,
1417 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1419 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1420 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1421 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1426 * Move filecaps structure to the new place and clear the old place.
1429 filecaps_move(struct filecaps *src, struct filecaps *dst)
1433 bzero(src, sizeof(*src));
1437 * Fill the given filecaps structure with full rights.
1440 filecaps_fill(struct filecaps *fcaps)
1443 CAP_ALL(&fcaps->fc_rights);
1444 fcaps->fc_ioctls = NULL;
1445 fcaps->fc_nioctls = -1;
1446 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1450 * Free memory allocated within filecaps structure.
1453 filecaps_free(struct filecaps *fcaps)
1456 free(fcaps->fc_ioctls, M_FILECAPS);
1457 bzero(fcaps, sizeof(*fcaps));
1461 * Validate the given filecaps structure.
1464 filecaps_validate(const struct filecaps *fcaps, const char *func)
1467 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1468 ("%s: invalid rights", func));
1469 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1470 ("%s: invalid fcntls", func));
1471 KASSERT(fcaps->fc_fcntls == 0 ||
1472 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1473 ("%s: fcntls without CAP_FCNTL", func));
1474 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1475 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1476 ("%s: invalid ioctls", func));
1477 KASSERT(fcaps->fc_nioctls == 0 ||
1478 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1479 ("%s: ioctls without CAP_IOCTL", func));
1483 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1487 FILEDESC_XLOCK_ASSERT(fdp);
1489 nfd1 = fdp->fd_nfiles * 2;
1492 fdgrowtable(fdp, nfd1);
1496 * Grow the file table to accomodate (at least) nfd descriptors.
1499 fdgrowtable(struct filedesc *fdp, int nfd)
1501 struct filedesc0 *fdp0;
1502 struct freetable *ft;
1503 struct filedescent *ntable;
1504 struct filedescent *otable;
1505 int nnfiles, onfiles;
1506 NDSLOTTYPE *nmap, *omap;
1508 FILEDESC_XLOCK_ASSERT(fdp);
1510 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1512 /* save old values */
1513 onfiles = fdp->fd_nfiles;
1514 otable = fdp->fd_ofiles;
1517 /* compute the size of the new table */
1518 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1519 if (nnfiles <= onfiles)
1520 /* the table is already large enough */
1524 * Allocate a new table and map. We need enough space for the
1525 * file entries themselves and the struct freetable we will use
1526 * when we decommission the table and place it on the freelist.
1527 * We place the struct freetable in the middle so we don't have
1528 * to worry about padding.
1530 ntable = malloc(nnfiles * sizeof(ntable[0]) + sizeof(struct freetable),
1531 M_FILEDESC, M_ZERO | M_WAITOK);
1532 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1535 /* copy the old data over and point at the new tables */
1536 memcpy(ntable, otable, onfiles * sizeof(*otable));
1537 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1539 /* update the pointers and counters */
1540 memcpy(ntable, otable, onfiles * sizeof(ntable[0]));
1541 fdp->fd_ofiles = ntable;
1545 * In order to have a valid pattern for fget_unlocked()
1546 * fdp->fd_nfiles must be the last member to be updated, otherwise
1547 * fget_unlocked() consumers may reference a new, higher value for
1548 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1549 * resulting in OOB accesses.
1551 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1554 * Do not free the old file table, as some threads may still
1555 * reference entries within it. Instead, place it on a freelist
1556 * which will be processed when the struct filedesc is released.
1558 * Do, however, free the old map.
1560 * Note that if onfiles == NDFILE, we're dealing with the original
1561 * static allocation contained within (struct filedesc0 *)fdp,
1562 * which must not be freed.
1564 if (onfiles > NDFILE) {
1565 ft = (struct freetable *)&otable[onfiles];
1566 fdp0 = (struct filedesc0 *)fdp;
1567 ft->ft_table = otable;
1568 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1569 free(omap, M_FILEDESC);
1574 * Allocate a file descriptor for the process.
1577 fdalloc(struct thread *td, int minfd, int *result)
1579 struct proc *p = td->td_proc;
1580 struct filedesc *fdp = p->p_fd;
1581 int fd = -1, maxfd, allocfd;
1586 FILEDESC_XLOCK_ASSERT(fdp);
1588 if (fdp->fd_freefile > minfd)
1589 minfd = fdp->fd_freefile;
1591 maxfd = getmaxfd(p);
1594 * Search the bitmap for a free descriptor starting at minfd.
1595 * If none is found, grow the file table.
1597 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1600 if (fd >= fdp->fd_nfiles) {
1601 allocfd = min(fd * 2, maxfd);
1604 error = racct_set(p, RACCT_NOFILE, allocfd);
1610 * fd is already equal to first free descriptor >= minfd, so
1611 * we only need to grow the table and we are done.
1613 fdgrowtable_exp(fdp, allocfd);
1617 * Perform some sanity checks, then mark the file descriptor as
1618 * used and return it to the caller.
1620 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1621 ("invalid descriptor %d", fd));
1622 KASSERT(!fdisused(fdp, fd),
1623 ("fd_first_free() returned non-free descriptor"));
1624 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1625 ("file descriptor isn't free"));
1626 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1633 * Allocate n file descriptors for the process.
1636 fdallocn(struct thread *td, int minfd, int *fds, int n)
1638 struct proc *p = td->td_proc;
1639 struct filedesc *fdp = p->p_fd;
1642 FILEDESC_XLOCK_ASSERT(fdp);
1644 if (!fdavail(td, n))
1647 for (i = 0; i < n; i++)
1648 if (fdalloc(td, 0, &fds[i]) != 0)
1652 for (i--; i >= 0; i--)
1653 fdunused(fdp, fds[i]);
1661 * Check to see whether n user file descriptors are available to the process
1665 fdavail(struct thread *td, int n)
1667 struct proc *p = td->td_proc;
1668 struct filedesc *fdp = td->td_proc->p_fd;
1671 FILEDESC_LOCK_ASSERT(fdp);
1674 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1675 * call racct_add() from there instead of dealing with containers
1679 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1681 last = min(fdp->fd_nfiles, lim);
1682 for (i = fdp->fd_freefile; i < last; i++) {
1683 if (fdp->fd_ofiles[i].fde_file == NULL && --n <= 0)
1690 * Create a new open file structure and allocate a file decriptor for the
1691 * process that refers to it. We add one reference to the file for the
1692 * descriptor table and one reference for resultfp. This is to prevent us
1693 * being preempted and the entry in the descriptor table closed after we
1694 * release the FILEDESC lock.
1697 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1702 error = falloc_noinstall(td, &fp);
1704 return (error); /* no reference held on error */
1706 error = finstall(td, fp, &fd, flags, NULL);
1708 fdrop(fp, td); /* one reference (fp only) */
1712 if (resultfp != NULL)
1713 *resultfp = fp; /* copy out result */
1715 fdrop(fp, td); /* release local reference */
1717 if (resultfd != NULL)
1724 * Create a new open file structure without allocating a file descriptor.
1727 falloc_noinstall(struct thread *td, struct file **resultfp)
1730 int maxuserfiles = maxfiles - (maxfiles / 20);
1731 static struct timeval lastfail;
1734 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1736 if ((openfiles >= maxuserfiles &&
1737 priv_check(td, PRIV_MAXFILES) != 0) ||
1738 openfiles >= maxfiles) {
1739 if (ppsratecheck(&lastfail, &curfail, 1)) {
1740 printf("kern.maxfiles limit exceeded by uid %i, "
1741 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1745 atomic_add_int(&openfiles, 1);
1746 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1747 refcount_init(&fp->f_count, 1);
1748 fp->f_cred = crhold(td->td_ucred);
1749 fp->f_ops = &badfileops;
1757 * Install a file in a file descriptor table.
1760 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1761 struct filecaps *fcaps)
1763 struct filedesc *fdp = td->td_proc->p_fd;
1764 struct filedescent *fde;
1767 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1768 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1770 filecaps_validate(fcaps, __func__);
1772 FILEDESC_XLOCK(fdp);
1773 if ((error = fdalloc(td, 0, fd))) {
1774 FILEDESC_XUNLOCK(fdp);
1778 fde = &fdp->fd_ofiles[*fd];
1780 if ((flags & O_CLOEXEC) != 0)
1781 fde->fde_flags |= UF_EXCLOSE;
1783 filecaps_move(fcaps, &fde->fde_caps);
1785 filecaps_fill(&fde->fde_caps);
1786 FILEDESC_XUNLOCK(fdp);
1791 * Build a new filedesc structure from another.
1792 * Copy the current, root, and jail root vnode references.
1795 fdinit(struct filedesc *fdp)
1797 struct filedesc0 *newfdp;
1799 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1800 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1802 FILEDESC_XLOCK(fdp);
1803 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1804 if (newfdp->fd_fd.fd_cdir)
1805 VREF(newfdp->fd_fd.fd_cdir);
1806 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1807 if (newfdp->fd_fd.fd_rdir)
1808 VREF(newfdp->fd_fd.fd_rdir);
1809 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1810 if (newfdp->fd_fd.fd_jdir)
1811 VREF(newfdp->fd_fd.fd_jdir);
1812 FILEDESC_XUNLOCK(fdp);
1815 /* Create the file descriptor table. */
1816 newfdp->fd_fd.fd_refcnt = 1;
1817 newfdp->fd_fd.fd_holdcnt = 1;
1818 newfdp->fd_fd.fd_cmask = CMASK;
1819 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1820 newfdp->fd_fd.fd_nfiles = NDFILE;
1821 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1822 newfdp->fd_fd.fd_lastfile = -1;
1823 return (&newfdp->fd_fd);
1826 static struct filedesc *
1827 fdhold(struct proc *p)
1829 struct filedesc *fdp;
1831 mtx_lock(&fdesc_mtx);
1835 mtx_unlock(&fdesc_mtx);
1840 fddrop(struct filedesc *fdp)
1842 struct filedesc0 *fdp0;
1843 struct freetable *ft;
1846 mtx_lock(&fdesc_mtx);
1847 i = --fdp->fd_holdcnt;
1848 mtx_unlock(&fdesc_mtx);
1852 FILEDESC_LOCK_DESTROY(fdp);
1853 fdp0 = (struct filedesc0 *)fdp;
1854 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1855 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1856 free(ft->ft_table, M_FILEDESC);
1858 free(fdp, M_FILEDESC);
1862 * Share a filedesc structure.
1865 fdshare(struct filedesc *fdp)
1868 FILEDESC_XLOCK(fdp);
1870 FILEDESC_XUNLOCK(fdp);
1875 * Unshare a filedesc structure, if necessary by making a copy
1878 fdunshare(struct proc *p, struct thread *td)
1881 FILEDESC_XLOCK(p->p_fd);
1882 if (p->p_fd->fd_refcnt > 1) {
1883 struct filedesc *tmp;
1885 FILEDESC_XUNLOCK(p->p_fd);
1886 tmp = fdcopy(p->p_fd);
1890 FILEDESC_XUNLOCK(p->p_fd);
1894 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1895 * this is to ease callers, not catch errors.
1898 fdcopy(struct filedesc *fdp)
1900 struct filedesc *newfdp;
1901 struct filedescent *nfde, *ofde;
1904 /* Certain daemons might not have file descriptors. */
1908 newfdp = fdinit(fdp);
1909 FILEDESC_SLOCK(fdp);
1910 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1911 FILEDESC_SUNLOCK(fdp);
1912 FILEDESC_XLOCK(newfdp);
1913 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1914 FILEDESC_XUNLOCK(newfdp);
1915 FILEDESC_SLOCK(fdp);
1917 /* copy all passable descriptors (i.e. not kqueue) */
1918 newfdp->fd_freefile = -1;
1919 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1920 ofde = &fdp->fd_ofiles[i];
1921 if (fdisused(fdp, i) &&
1922 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1923 ofde->fde_file->f_ops != &badfileops) {
1924 nfde = &newfdp->fd_ofiles[i];
1926 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1927 fhold(nfde->fde_file);
1928 newfdp->fd_lastfile = i;
1930 if (newfdp->fd_freefile == -1)
1931 newfdp->fd_freefile = i;
1934 newfdp->fd_cmask = fdp->fd_cmask;
1935 FILEDESC_SUNLOCK(fdp);
1936 FILEDESC_XLOCK(newfdp);
1937 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1938 if (newfdp->fd_ofiles[i].fde_file != NULL)
1941 if (newfdp->fd_freefile == -1)
1942 newfdp->fd_freefile = i;
1943 FILEDESC_XUNLOCK(newfdp);
1948 * Release a filedesc structure.
1951 fdescfree(struct thread *td)
1953 struct filedesc *fdp;
1955 struct filedesc_to_leader *fdtol;
1957 struct vnode *cdir, *jdir, *rdir, *vp;
1960 /* Certain daemons might not have file descriptors. */
1961 fdp = td->td_proc->p_fd;
1966 PROC_LOCK(td->td_proc);
1967 racct_set(td->td_proc, RACCT_NOFILE, 0);
1968 PROC_UNLOCK(td->td_proc);
1971 /* Check for special need to clear POSIX style locks */
1972 fdtol = td->td_proc->p_fdtol;
1973 if (fdtol != NULL) {
1974 FILEDESC_XLOCK(fdp);
1975 KASSERT(fdtol->fdl_refcount > 0,
1976 ("filedesc_to_refcount botch: fdl_refcount=%d",
1977 fdtol->fdl_refcount));
1978 if (fdtol->fdl_refcount == 1 &&
1979 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1980 for (i = 0; i <= fdp->fd_lastfile; i++) {
1981 fp = fdp->fd_ofiles[i].fde_file;
1982 if (fp == NULL || fp->f_type != DTYPE_VNODE)
1985 FILEDESC_XUNLOCK(fdp);
1986 lf.l_whence = SEEK_SET;
1989 lf.l_type = F_UNLCK;
1991 (void) VOP_ADVLOCK(vp,
1992 (caddr_t)td->td_proc->p_leader, F_UNLCK,
1994 FILEDESC_XLOCK(fdp);
1999 if (fdtol->fdl_refcount == 1) {
2000 if (fdp->fd_holdleaderscount > 0 &&
2001 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2003 * close() or do_dup() has cleared a reference
2004 * in a shared file descriptor table.
2006 fdp->fd_holdleaderswakeup = 1;
2007 sx_sleep(&fdp->fd_holdleaderscount,
2008 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2011 if (fdtol->fdl_holdcount > 0) {
2013 * Ensure that fdtol->fdl_leader remains
2014 * valid in closef().
2016 fdtol->fdl_wakeup = 1;
2017 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2022 fdtol->fdl_refcount--;
2023 if (fdtol->fdl_refcount == 0 &&
2024 fdtol->fdl_holdcount == 0) {
2025 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2026 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2029 td->td_proc->p_fdtol = NULL;
2030 FILEDESC_XUNLOCK(fdp);
2032 free(fdtol, M_FILEDESC_TO_LEADER);
2034 FILEDESC_XLOCK(fdp);
2035 i = --fdp->fd_refcnt;
2036 FILEDESC_XUNLOCK(fdp);
2040 for (i = 0; i <= fdp->fd_lastfile; i++) {
2041 fp = fdp->fd_ofiles[i].fde_file;
2043 FILEDESC_XLOCK(fdp);
2045 FILEDESC_XUNLOCK(fdp);
2046 (void) closef(fp, td);
2049 FILEDESC_XLOCK(fdp);
2051 /* XXX This should happen earlier. */
2052 mtx_lock(&fdesc_mtx);
2053 td->td_proc->p_fd = NULL;
2054 mtx_unlock(&fdesc_mtx);
2056 if (fdp->fd_nfiles > NDFILE)
2057 free(fdp->fd_ofiles, M_FILEDESC);
2058 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2059 free(fdp->fd_map, M_FILEDESC);
2063 cdir = fdp->fd_cdir;
2064 fdp->fd_cdir = NULL;
2065 rdir = fdp->fd_rdir;
2066 fdp->fd_rdir = NULL;
2067 jdir = fdp->fd_jdir;
2068 fdp->fd_jdir = NULL;
2069 FILEDESC_XUNLOCK(fdp);
2082 * For setugid programs, we don't want to people to use that setugidness
2083 * to generate error messages which write to a file which otherwise would
2084 * otherwise be off-limits to the process. We check for filesystems where
2085 * the vnode can change out from under us after execve (like [lin]procfs).
2087 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2088 * sufficient. We also don't check for setugidness since we know we are.
2091 is_unsafe(struct file *fp)
2093 if (fp->f_type == DTYPE_VNODE) {
2094 struct vnode *vp = fp->f_vnode;
2096 if ((vp->v_vflag & VV_PROCDEP) != 0)
2103 * Make this setguid thing safe, if at all possible.
2106 setugidsafety(struct thread *td)
2108 struct filedesc *fdp;
2112 /* Certain daemons might not have file descriptors. */
2113 fdp = td->td_proc->p_fd;
2118 * Note: fdp->fd_ofiles may be reallocated out from under us while
2119 * we are blocked in a close. Be careful!
2121 FILEDESC_XLOCK(fdp);
2122 for (i = 0; i <= fdp->fd_lastfile; i++) {
2125 fp = fdp->fd_ofiles[i].fde_file;
2126 if (fp != NULL && is_unsafe(fp)) {
2127 knote_fdclose(td, i);
2129 * NULL-out descriptor prior to close to avoid
2130 * a race while close blocks.
2133 FILEDESC_XUNLOCK(fdp);
2134 (void) closef(fp, td);
2135 FILEDESC_XLOCK(fdp);
2138 FILEDESC_XUNLOCK(fdp);
2142 * If a specific file object occupies a specific file descriptor, close the
2143 * file descriptor entry and drop a reference on the file object. This is a
2144 * convenience function to handle a subsequent error in a function that calls
2145 * falloc() that handles the race that another thread might have closed the
2146 * file descriptor out from under the thread creating the file object.
2149 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2152 FILEDESC_XLOCK(fdp);
2153 if (fdp->fd_ofiles[idx].fde_file == fp) {
2155 FILEDESC_XUNLOCK(fdp);
2158 FILEDESC_XUNLOCK(fdp);
2162 * Close any files on exec?
2165 fdcloseexec(struct thread *td)
2167 struct filedesc *fdp;
2168 struct filedescent *fde;
2172 /* Certain daemons might not have file descriptors. */
2173 fdp = td->td_proc->p_fd;
2178 * We cannot cache fd_ofiles since operations
2179 * may block and rip them out from under us.
2181 FILEDESC_XLOCK(fdp);
2182 for (i = 0; i <= fdp->fd_lastfile; i++) {
2183 fde = &fdp->fd_ofiles[i];
2185 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2186 (fde->fde_flags & UF_EXCLOSE))) {
2188 (void) closefp(fdp, i, fp, td, 0);
2189 /* closefp() drops the FILEDESC lock. */
2190 FILEDESC_XLOCK(fdp);
2193 FILEDESC_XUNLOCK(fdp);
2197 * It is unsafe for set[ug]id processes to be started with file
2198 * descriptors 0..2 closed, as these descriptors are given implicit
2199 * significance in the Standard C library. fdcheckstd() will create a
2200 * descriptor referencing /dev/null for each of stdin, stdout, and
2201 * stderr that is not already open.
2204 fdcheckstd(struct thread *td)
2206 struct filedesc *fdp;
2207 register_t retval, save;
2208 int i, error, devnull;
2210 fdp = td->td_proc->p_fd;
2213 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2216 for (i = 0; i < 3; i++) {
2217 if (fdp->fd_ofiles[i].fde_file != NULL)
2220 save = td->td_retval[0];
2221 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2223 devnull = td->td_retval[0];
2224 td->td_retval[0] = save;
2227 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2229 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2238 * Internal form of close. Decrement reference count on file structure.
2239 * Note: td may be NULL when closing a file that was being passed in a
2242 * XXXRW: Giant is not required for the caller, but often will be held; this
2243 * makes it moderately likely the Giant will be recursed in the VFS case.
2246 closef(struct file *fp, struct thread *td)
2250 struct filedesc_to_leader *fdtol;
2251 struct filedesc *fdp;
2254 * POSIX record locking dictates that any close releases ALL
2255 * locks owned by this process. This is handled by setting
2256 * a flag in the unlock to free ONLY locks obeying POSIX
2257 * semantics, and not to free BSD-style file locks.
2258 * If the descriptor was in a message, POSIX-style locks
2259 * aren't passed with the descriptor, and the thread pointer
2260 * will be NULL. Callers should be careful only to pass a
2261 * NULL thread pointer when there really is no owning
2262 * context that might have locks, or the locks will be
2265 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2267 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2268 lf.l_whence = SEEK_SET;
2271 lf.l_type = F_UNLCK;
2272 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2273 F_UNLCK, &lf, F_POSIX);
2275 fdtol = td->td_proc->p_fdtol;
2276 if (fdtol != NULL) {
2278 * Handle special case where file descriptor table is
2279 * shared between multiple process leaders.
2281 fdp = td->td_proc->p_fd;
2282 FILEDESC_XLOCK(fdp);
2283 for (fdtol = fdtol->fdl_next;
2284 fdtol != td->td_proc->p_fdtol;
2285 fdtol = fdtol->fdl_next) {
2286 if ((fdtol->fdl_leader->p_flag &
2289 fdtol->fdl_holdcount++;
2290 FILEDESC_XUNLOCK(fdp);
2291 lf.l_whence = SEEK_SET;
2294 lf.l_type = F_UNLCK;
2296 (void) VOP_ADVLOCK(vp,
2297 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2299 FILEDESC_XLOCK(fdp);
2300 fdtol->fdl_holdcount--;
2301 if (fdtol->fdl_holdcount == 0 &&
2302 fdtol->fdl_wakeup != 0) {
2303 fdtol->fdl_wakeup = 0;
2307 FILEDESC_XUNLOCK(fdp);
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, cap_rights_t *needrightsp,
2331 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2336 cap_rights_t haverights;
2341 * Avoid reads reordering and then a first access to the
2342 * fdp->fd_ofiles table which could result in OOB operation.
2344 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2347 * Fetch the descriptor locklessly. We avoid fdrop() races by
2348 * never raising a refcount above 0. To accomplish this we have
2349 * to use a cmpset loop rather than an atomic_add. The descriptor
2350 * must be re-verified once we acquire a reference to be certain
2351 * that the identity is still correct and we did not lose a race
2352 * due to preemption.
2355 fp = fdp->fd_ofiles[fd].fde_file;
2359 haverights = *cap_rights(fdp, fd);
2360 if (needrightsp != NULL) {
2361 error = cap_check(&haverights, needrightsp);
2364 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2365 error = cap_fcntl_check(fdp, fd, needfcntl);
2371 count = fp->f_count;
2375 * Use an acquire barrier to prevent caching of fd_ofiles
2376 * so it is refreshed for verification.
2378 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2380 if (fp == fdp->fd_ofiles[fd].fde_file)
2382 fdrop(fp, curthread);
2385 if (haverightsp != NULL) {
2387 *haverightsp = haverights;
2389 CAP_ALL(haverightsp);
2396 * Extract the file pointer associated with the specified descriptor for the
2397 * current user process.
2399 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2402 * File's rights will be checked against the capability rights mask.
2404 * If an error occured the non-zero error is returned and *fpp is set to
2405 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2406 * responsible for fdrop().
2409 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2410 cap_rights_t *needrightsp, u_char *maxprotp)
2412 struct filedesc *fdp;
2414 cap_rights_t haverights, needrights;
2418 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2420 if (needrightsp != NULL)
2421 needrights = *needrightsp;
2423 cap_rights_init(&needrights);
2424 if (maxprotp != NULL)
2425 cap_rights_set(&needrights, CAP_MMAP);
2426 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2429 if (fp->f_ops == &badfileops) {
2436 * If requested, convert capability rights to access flags.
2438 if (maxprotp != NULL)
2439 *maxprotp = cap_rights_to_vmprot(&haverights);
2440 #else /* !CAPABILITIES */
2441 if (maxprotp != NULL)
2442 *maxprotp = VM_PROT_ALL;
2443 #endif /* CAPABILITIES */
2446 * FREAD and FWRITE failure return EBADF as per POSIX.
2452 if ((fp->f_flag & flags) == 0)
2456 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2457 ((fp->f_flag & FWRITE) != 0))
2463 KASSERT(0, ("wrong flags"));
2476 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2479 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2483 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2487 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2491 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2494 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2498 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2501 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2505 * Like fget() but loads the underlying vnode, or returns an error if the
2506 * descriptor does not represent a vnode. Note that pipes use vnodes but
2507 * never have VM objects. The returned vnode will be vref()'d.
2509 * XXX: what about the unused flags ?
2512 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2519 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2522 if (fp->f_vnode == NULL) {
2534 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2537 return (_fgetvp(td, fd, 0, rightsp, vpp));
2541 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2542 struct filecaps *havecaps, struct vnode **vpp)
2544 struct filedesc *fdp;
2550 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2553 fp = fget_locked(fdp, fd);
2554 if (fp == NULL || fp->f_ops == &badfileops)
2558 if (needrightsp != NULL) {
2559 error = cap_check(cap_rights(fdp, fd), needrightsp);
2565 if (fp->f_vnode == NULL)
2570 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2576 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2579 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2583 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2586 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2591 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2595 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2600 * Like fget() but loads the underlying socket, or returns an error if the
2601 * descriptor does not represent a socket.
2603 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2606 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2607 * on their file descriptor reference to prevent the socket from being free'd
2611 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2620 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2622 if (fp->f_type != DTYPE_SOCKET) {
2627 *fflagp = fp->f_flag;
2638 * Drop the reference count on the socket and XXX release the SX lock in the
2639 * future. The last reference closes the socket.
2641 * Note: fputsock() is deprecated, see comment for fgetsock().
2644 fputsock(struct socket *so)
2649 CURVNET_SET(so->so_vnet);
2655 * Handle the last reference to a file being closed.
2658 _fdrop(struct file *fp, struct thread *td)
2663 if (fp->f_count != 0)
2664 panic("fdrop: count %d", fp->f_count);
2665 if (fp->f_ops != &badfileops)
2666 error = fo_close(fp, td);
2667 atomic_subtract_int(&openfiles, 1);
2669 free(fp->f_advice, M_FADVISE);
2670 uma_zfree(file_zone, fp);
2676 * Apply an advisory lock on a file descriptor.
2678 * Just attempt to get a record lock of the requested type on the entire file
2679 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2681 #ifndef _SYS_SYSPROTO_H_
2689 sys_flock(struct thread *td, struct flock_args *uap)
2694 cap_rights_t rights;
2697 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2700 if (fp->f_type != DTYPE_VNODE) {
2702 return (EOPNOTSUPP);
2706 lf.l_whence = SEEK_SET;
2709 if (uap->how & LOCK_UN) {
2710 lf.l_type = F_UNLCK;
2711 atomic_clear_int(&fp->f_flag, FHASLOCK);
2712 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2715 if (uap->how & LOCK_EX)
2716 lf.l_type = F_WRLCK;
2717 else if (uap->how & LOCK_SH)
2718 lf.l_type = F_RDLCK;
2723 atomic_set_int(&fp->f_flag, FHASLOCK);
2724 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2725 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2731 * Duplicate the specified descriptor to a free descriptor.
2734 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2735 int openerror, int *indxp)
2740 KASSERT(openerror == ENODEV || openerror == ENXIO,
2741 ("unexpected error %d in %s", openerror, __func__));
2744 * If the to-be-dup'd fd number is greater than the allowed number
2745 * of file descriptors, or the fd to be dup'd has already been
2746 * closed, then reject.
2748 FILEDESC_XLOCK(fdp);
2749 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2750 FILEDESC_XUNLOCK(fdp);
2754 error = fdalloc(td, 0, &indx);
2756 FILEDESC_XUNLOCK(fdp);
2761 * There are two cases of interest here.
2763 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2765 * For ENXIO steal away the file structure from (dfd) and store it in
2766 * (indx). (dfd) is effectively closed by this operation.
2768 switch (openerror) {
2771 * Check that the mode the file is being opened for is a
2772 * subset of the mode of the existing descriptor.
2774 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2775 fdunused(fdp, indx);
2776 FILEDESC_XUNLOCK(fdp);
2780 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2781 filecaps_copy(&fdp->fd_ofiles[dfd].fde_caps,
2782 &fdp->fd_ofiles[indx].fde_caps);
2786 * Steal away the file pointer from dfd and stuff it into indx.
2788 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2789 bzero(&fdp->fd_ofiles[dfd], sizeof(fdp->fd_ofiles[dfd]));
2793 FILEDESC_XUNLOCK(fdp);
2799 * Scan all active processes and prisons to see if any of them have a current
2800 * or root directory of `olddp'. If so, replace them with the new mount point.
2803 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2805 struct filedesc *fdp;
2810 if (vrefcnt(olddp) == 1)
2813 sx_slock(&allproc_lock);
2814 FOREACH_PROC_IN_SYSTEM(p) {
2818 FILEDESC_XLOCK(fdp);
2819 if (fdp->fd_cdir == olddp) {
2821 fdp->fd_cdir = newdp;
2824 if (fdp->fd_rdir == olddp) {
2826 fdp->fd_rdir = newdp;
2829 if (fdp->fd_jdir == olddp) {
2831 fdp->fd_jdir = newdp;
2834 FILEDESC_XUNLOCK(fdp);
2837 sx_sunlock(&allproc_lock);
2838 if (rootvnode == olddp) {
2843 mtx_lock(&prison0.pr_mtx);
2844 if (prison0.pr_root == olddp) {
2846 prison0.pr_root = newdp;
2849 mtx_unlock(&prison0.pr_mtx);
2850 sx_slock(&allprison_lock);
2851 TAILQ_FOREACH(pr, &allprison, pr_list) {
2852 mtx_lock(&pr->pr_mtx);
2853 if (pr->pr_root == olddp) {
2855 pr->pr_root = newdp;
2858 mtx_unlock(&pr->pr_mtx);
2860 sx_sunlock(&allprison_lock);
2865 struct filedesc_to_leader *
2866 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2868 struct filedesc_to_leader *fdtol;
2870 fdtol = malloc(sizeof(struct filedesc_to_leader),
2871 M_FILEDESC_TO_LEADER,
2873 fdtol->fdl_refcount = 1;
2874 fdtol->fdl_holdcount = 0;
2875 fdtol->fdl_wakeup = 0;
2876 fdtol->fdl_leader = leader;
2878 FILEDESC_XLOCK(fdp);
2879 fdtol->fdl_next = old->fdl_next;
2880 fdtol->fdl_prev = old;
2881 old->fdl_next = fdtol;
2882 fdtol->fdl_next->fdl_prev = fdtol;
2883 FILEDESC_XUNLOCK(fdp);
2885 fdtol->fdl_next = fdtol;
2886 fdtol->fdl_prev = fdtol;
2892 * Get file structures globally.
2895 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2898 struct filedesc *fdp;
2903 error = sysctl_wire_old_buffer(req, 0);
2906 if (req->oldptr == NULL) {
2908 sx_slock(&allproc_lock);
2909 FOREACH_PROC_IN_SYSTEM(p) {
2910 if (p->p_state == PRS_NEW)
2915 /* overestimates sparse tables. */
2916 if (fdp->fd_lastfile > 0)
2917 n += fdp->fd_lastfile;
2920 sx_sunlock(&allproc_lock);
2921 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2924 bzero(&xf, sizeof(xf));
2925 xf.xf_size = sizeof(xf);
2926 sx_slock(&allproc_lock);
2927 FOREACH_PROC_IN_SYSTEM(p) {
2929 if (p->p_state == PRS_NEW) {
2933 if (p_cansee(req->td, p) != 0) {
2937 xf.xf_pid = p->p_pid;
2938 xf.xf_uid = p->p_ucred->cr_uid;
2943 FILEDESC_SLOCK(fdp);
2944 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2945 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
2949 xf.xf_data = fp->f_data;
2950 xf.xf_vnode = fp->f_vnode;
2951 xf.xf_type = fp->f_type;
2952 xf.xf_count = fp->f_count;
2954 xf.xf_offset = foffset_get(fp);
2955 xf.xf_flag = fp->f_flag;
2956 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2960 FILEDESC_SUNLOCK(fdp);
2965 sx_sunlock(&allproc_lock);
2969 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2970 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2972 #ifdef KINFO_OFILE_SIZE
2973 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2976 #ifdef COMPAT_FREEBSD7
2978 export_vnode_for_osysctl(struct vnode *vp, int type,
2979 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2982 char *fullpath, *freepath;
2984 bzero(kif, sizeof(*kif));
2985 kif->kf_structsize = sizeof(*kif);
2989 kif->kf_type = KF_TYPE_VNODE;
2990 /* This function only handles directories. */
2991 if (vp->v_type != VDIR) {
2995 kif->kf_vnode_type = KF_VTYPE_VDIR;
2998 * This is not a true file descriptor, so we set a bogus refcount
2999 * and offset to indicate these fields should be ignored.
3001 kif->kf_ref_count = -1;
3002 kif->kf_offset = -1;
3006 FILEDESC_SUNLOCK(fdp);
3007 vn_fullpath(curthread, vp, &fullpath, &freepath);
3009 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3010 if (freepath != NULL)
3011 free(freepath, M_TEMP);
3012 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3013 FILEDESC_SLOCK(fdp);
3018 * Get per-process file descriptors for use by procstat(1), et al.
3021 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3023 char *fullpath, *freepath;
3024 struct kinfo_ofile *kif;
3025 struct filedesc *fdp;
3026 int error, i, *name;
3027 struct shmfd *shmfd;
3036 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3043 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3044 FILEDESC_SLOCK(fdp);
3045 if (fdp->fd_cdir != NULL)
3046 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3048 if (fdp->fd_rdir != NULL)
3049 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3051 if (fdp->fd_jdir != NULL)
3052 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3054 for (i = 0; i < fdp->fd_nfiles; i++) {
3055 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3057 bzero(kif, sizeof(*kif));
3058 kif->kf_structsize = sizeof(*kif);
3066 switch (fp->f_type) {
3068 kif->kf_type = KF_TYPE_VNODE;
3073 kif->kf_type = KF_TYPE_SOCKET;
3078 kif->kf_type = KF_TYPE_PIPE;
3082 kif->kf_type = KF_TYPE_FIFO;
3087 kif->kf_type = KF_TYPE_KQUEUE;
3091 kif->kf_type = KF_TYPE_CRYPTO;
3095 kif->kf_type = KF_TYPE_MQUEUE;
3099 kif->kf_type = KF_TYPE_SHM;
3104 kif->kf_type = KF_TYPE_SEM;
3109 kif->kf_type = KF_TYPE_PTS;
3114 case DTYPE_PROCDESC:
3115 kif->kf_type = KF_TYPE_PROCDESC;
3120 kif->kf_type = KF_TYPE_UNKNOWN;
3123 kif->kf_ref_count = fp->f_count;
3124 if (fp->f_flag & FREAD)
3125 kif->kf_flags |= KF_FLAG_READ;
3126 if (fp->f_flag & FWRITE)
3127 kif->kf_flags |= KF_FLAG_WRITE;
3128 if (fp->f_flag & FAPPEND)
3129 kif->kf_flags |= KF_FLAG_APPEND;
3130 if (fp->f_flag & FASYNC)
3131 kif->kf_flags |= KF_FLAG_ASYNC;
3132 if (fp->f_flag & FFSYNC)
3133 kif->kf_flags |= KF_FLAG_FSYNC;
3134 if (fp->f_flag & FNONBLOCK)
3135 kif->kf_flags |= KF_FLAG_NONBLOCK;
3136 if (fp->f_flag & O_DIRECT)
3137 kif->kf_flags |= KF_FLAG_DIRECT;
3138 if (fp->f_flag & FHASLOCK)
3139 kif->kf_flags |= KF_FLAG_HASLOCK;
3140 kif->kf_offset = foffset_get(fp);
3143 switch (vp->v_type) {
3145 kif->kf_vnode_type = KF_VTYPE_VNON;
3148 kif->kf_vnode_type = KF_VTYPE_VREG;
3151 kif->kf_vnode_type = KF_VTYPE_VDIR;
3154 kif->kf_vnode_type = KF_VTYPE_VBLK;
3157 kif->kf_vnode_type = KF_VTYPE_VCHR;
3160 kif->kf_vnode_type = KF_VTYPE_VLNK;
3163 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3166 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3169 kif->kf_vnode_type = KF_VTYPE_VBAD;
3172 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3176 * It is OK to drop the filedesc lock here as we will
3177 * re-validate and re-evaluate its properties when
3178 * the loop continues.
3182 FILEDESC_SUNLOCK(fdp);
3183 vn_fullpath(curthread, vp, &fullpath, &freepath);
3185 strlcpy(kif->kf_path, fullpath,
3186 sizeof(kif->kf_path));
3187 if (freepath != NULL)
3188 free(freepath, M_TEMP);
3189 FILEDESC_SLOCK(fdp);
3192 struct sockaddr *sa;
3194 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3195 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3196 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3199 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3200 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3201 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3204 kif->kf_sock_domain =
3205 so->so_proto->pr_domain->dom_family;
3206 kif->kf_sock_type = so->so_type;
3207 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3210 strlcpy(kif->kf_path, tty_devname(tp),
3211 sizeof(kif->kf_path));
3214 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3215 if (ks != NULL && ksem_info != NULL)
3216 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3217 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3221 FILEDESC_SUNLOCK(fdp);
3227 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3228 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3229 #endif /* COMPAT_FREEBSD7 */
3231 #ifdef KINFO_FILE_SIZE
3232 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3235 struct export_fd_buf {
3236 struct filedesc *fdp;
3239 struct kinfo_file kif;
3243 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3244 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3249 } fflags_table[] = {
3250 { FAPPEND, KF_FLAG_APPEND },
3251 { FASYNC, KF_FLAG_ASYNC },
3252 { FFSYNC, KF_FLAG_FSYNC },
3253 { FHASLOCK, KF_FLAG_HASLOCK },
3254 { FNONBLOCK, KF_FLAG_NONBLOCK },
3255 { FREAD, KF_FLAG_READ },
3256 { FWRITE, KF_FLAG_WRITE },
3257 { O_CREAT, KF_FLAG_CREAT },
3258 { O_DIRECT, KF_FLAG_DIRECT },
3259 { O_EXCL, KF_FLAG_EXCL },
3260 { O_EXEC, KF_FLAG_EXEC },
3261 { O_EXLOCK, KF_FLAG_EXLOCK },
3262 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3263 { O_SHLOCK, KF_FLAG_SHLOCK },
3264 { O_TRUNC, KF_FLAG_TRUNC }
3266 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3267 struct kinfo_file *kif;
3272 if (efbuf->remainder == 0)
3275 bzero(kif, sizeof(*kif));
3276 locked = efbuf->fdp != NULL;
3281 FILEDESC_SUNLOCK(efbuf->fdp);
3284 vp = (struct vnode *)data;
3285 error = fill_vnode_info(vp, kif);
3288 case KF_TYPE_SOCKET:
3289 error = fill_socket_info((struct socket *)data, kif);
3292 error = fill_pipe_info((struct pipe *)data, kif);
3295 error = fill_pts_info((struct tty *)data, kif);
3297 case KF_TYPE_PROCDESC:
3298 error = fill_procdesc_info((struct procdesc *)data, kif);
3301 error = fill_sem_info((struct file *)data, kif);
3304 error = fill_shm_info((struct file *)data, kif);
3310 kif->kf_status |= KF_ATTR_VALID;
3313 * Translate file access flags.
3315 for (i = 0; i < NFFLAGS; i++)
3316 if (fflags & fflags_table[i].fflag)
3317 kif->kf_flags |= fflags_table[i].kf_fflag;
3318 if (rightsp != NULL)
3319 kif->kf_cap_rights = *rightsp;
3321 cap_rights_init(&kif->kf_cap_rights);
3323 kif->kf_type = type;
3324 kif->kf_ref_count = refcnt;
3325 kif->kf_offset = offset;
3326 /* Pack record size down */
3327 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3328 strlen(kif->kf_path) + 1;
3329 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3330 if (efbuf->remainder != -1) {
3331 if (efbuf->remainder < kif->kf_structsize) {
3332 /* Terminate export. */
3333 efbuf->remainder = 0;
3334 if (efbuf->fdp != NULL && !locked)
3335 FILEDESC_SLOCK(efbuf->fdp);
3338 efbuf->remainder -= kif->kf_structsize;
3341 FILEDESC_SUNLOCK(efbuf->fdp);
3342 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3343 if (efbuf->fdp != NULL)
3344 FILEDESC_SLOCK(efbuf->fdp);
3349 * Store a process file descriptor information to sbuf.
3351 * Takes a locked proc as argument, and returns with the proc unlocked.
3354 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3357 struct filedesc *fdp;
3358 struct export_fd_buf *efbuf;
3359 struct vnode *cttyvp, *textvp, *tracevp;
3363 int type, refcnt, fflags;
3364 cap_rights_t rights;
3366 PROC_LOCK_ASSERT(p, MA_OWNED);
3369 tracevp = p->p_tracevp;
3370 if (tracevp != NULL)
3373 textvp = p->p_textvp;
3376 /* Controlling tty. */
3378 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3379 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3385 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3388 efbuf->remainder = maxlen;
3389 if (tracevp != NULL)
3390 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3391 FREAD | FWRITE, -1, -1, NULL, efbuf);
3393 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3394 FREAD, -1, -1, NULL, efbuf);
3396 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3397 FREAD | FWRITE, -1, -1, NULL, efbuf);
3402 FILEDESC_SLOCK(fdp);
3403 /* working directory */
3404 if (fdp->fd_cdir != NULL) {
3406 data = fdp->fd_cdir;
3407 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3408 FREAD, -1, -1, NULL, efbuf);
3410 /* root directory */
3411 if (fdp->fd_rdir != NULL) {
3413 data = fdp->fd_rdir;
3414 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3415 FREAD, -1, -1, NULL, efbuf);
3417 /* jail directory */
3418 if (fdp->fd_jdir != NULL) {
3420 data = fdp->fd_jdir;
3421 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3422 FREAD, -1, -1, NULL, efbuf);
3424 for (i = 0; i < fdp->fd_nfiles; i++) {
3425 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3429 rights = *cap_rights(fdp, i);
3430 #else /* !CAPABILITIES */
3431 cap_rights_init(&rights);
3433 switch (fp->f_type) {
3435 type = KF_TYPE_VNODE;
3441 type = KF_TYPE_SOCKET;
3446 type = KF_TYPE_PIPE;
3451 type = KF_TYPE_FIFO;
3457 type = KF_TYPE_KQUEUE;
3461 type = KF_TYPE_CRYPTO;
3465 type = KF_TYPE_MQUEUE;
3484 case DTYPE_PROCDESC:
3485 type = KF_TYPE_PROCDESC;
3491 type = KF_TYPE_UNKNOWN;
3494 refcnt = fp->f_count;
3495 fflags = fp->f_flag;
3496 offset = foffset_get(fp);
3499 * Create sysctl entry.
3500 * It is OK to drop the filedesc lock here as we will
3501 * re-validate and re-evaluate its properties when
3502 * the loop continues.
3504 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3505 offset, &rights, efbuf);
3509 FILEDESC_SUNLOCK(fdp);
3512 free(efbuf, M_TEMP);
3516 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3519 * Get per-process file descriptors for use by procstat(1), et al.
3522 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3527 int error, error2, *name;
3531 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3532 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3537 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3538 error = kern_proc_filedesc_out(p, &sb, maxlen);
3539 error2 = sbuf_finish(&sb);
3541 return (error != 0 ? error : error2);
3545 vntype_to_kinfo(int vtype)
3550 } vtypes_table[] = {
3551 { VBAD, KF_VTYPE_VBAD },
3552 { VBLK, KF_VTYPE_VBLK },
3553 { VCHR, KF_VTYPE_VCHR },
3554 { VDIR, KF_VTYPE_VDIR },
3555 { VFIFO, KF_VTYPE_VFIFO },
3556 { VLNK, KF_VTYPE_VLNK },
3557 { VNON, KF_VTYPE_VNON },
3558 { VREG, KF_VTYPE_VREG },
3559 { VSOCK, KF_VTYPE_VSOCK }
3561 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3565 * Perform vtype translation.
3567 for (i = 0; i < NVTYPES; i++)
3568 if (vtypes_table[i].vtype == vtype)
3571 return (vtypes_table[i].kf_vtype);
3573 return (KF_VTYPE_UNKNOWN);
3577 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3580 char *fullpath, *freepath;
3585 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3588 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3590 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3592 if (freepath != NULL)
3593 free(freepath, M_TEMP);
3596 * Retrieve vnode attributes.
3598 va.va_fsid = VNOVAL;
3600 vn_lock(vp, LK_SHARED | LK_RETRY);
3601 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3605 if (va.va_fsid != VNOVAL)
3606 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3608 kif->kf_un.kf_file.kf_file_fsid =
3609 vp->v_mount->mnt_stat.f_fsid.val[0];
3610 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3611 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3612 kif->kf_un.kf_file.kf_file_size = va.va_size;
3613 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3618 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3620 struct sockaddr *sa;
3621 struct inpcb *inpcb;
3622 struct unpcb *unpcb;
3627 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3628 kif->kf_sock_type = so->so_type;
3629 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3630 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3631 switch(kif->kf_sock_domain) {
3634 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3635 if (so->so_pcb != NULL) {
3636 inpcb = (struct inpcb *)(so->so_pcb);
3637 kif->kf_un.kf_sock.kf_sock_inpcb =
3638 (uintptr_t)inpcb->inp_ppcb;
3643 if (so->so_pcb != NULL) {
3644 unpcb = (struct unpcb *)(so->so_pcb);
3645 if (unpcb->unp_conn) {
3646 kif->kf_un.kf_sock.kf_sock_unpconn =
3647 (uintptr_t)unpcb->unp_conn;
3648 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3649 so->so_rcv.sb_state;
3650 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3651 so->so_snd.sb_state;
3656 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3657 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3658 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3661 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3662 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3663 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3666 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3667 sizeof(kif->kf_path));
3672 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3677 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3678 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3683 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3688 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3689 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3690 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3695 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3700 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3705 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3711 if (fp->f_data == NULL)
3713 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3715 if (ksem_info == NULL)
3717 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3718 &kif->kf_un.kf_sem.kf_sem_value);
3719 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3724 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3730 if (fp->f_data == NULL)
3732 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3734 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3735 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3736 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3740 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3741 sysctl_kern_proc_filedesc, "Process filedesc entries");
3745 * For the purposes of debugging, generate a human-readable string for the
3749 file_type_to_name(short type)
3779 * For the purposes of debugging, identify a process (if any, perhaps one of
3780 * many) that references the passed file in its file descriptor array. Return
3783 static struct proc *
3784 file_to_first_proc(struct file *fp)
3786 struct filedesc *fdp;
3790 FOREACH_PROC_IN_SYSTEM(p) {
3791 if (p->p_state == PRS_NEW)
3796 for (n = 0; n < fdp->fd_nfiles; n++) {
3797 if (fp == fdp->fd_ofiles[n].fde_file)
3805 db_print_file(struct file *fp, int header)
3810 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3811 "File", "Type", "Data", "Flag", "GCFl", "Count",
3812 "MCount", "Vnode", "FPID", "FCmd");
3813 p = file_to_first_proc(fp);
3814 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3815 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3816 0, fp->f_count, 0, fp->f_vnode,
3817 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3820 DB_SHOW_COMMAND(file, db_show_file)
3825 db_printf("usage: show file <addr>\n");
3828 fp = (struct file *)addr;
3829 db_print_file(fp, 1);
3832 DB_SHOW_COMMAND(files, db_show_files)
3834 struct filedesc *fdp;
3841 FOREACH_PROC_IN_SYSTEM(p) {
3842 if (p->p_state == PRS_NEW)
3844 if ((fdp = p->p_fd) == NULL)
3846 for (n = 0; n < fdp->fd_nfiles; ++n) {
3847 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3849 db_print_file(fp, header);
3856 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3857 &maxfilesperproc, 0, "Maximum files allowed open per process");
3859 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3860 &maxfiles, 0, "Maximum number of files");
3862 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3863 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3867 filelistinit(void *dummy)
3870 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3871 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3872 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3873 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3875 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3877 /*-------------------------------------------------------------------*/
3880 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3881 int flags, struct thread *td)
3888 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3896 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3904 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3912 badfo_kqfilter(struct file *fp, struct knote *kn)
3919 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3927 badfo_close(struct file *fp, struct thread *td)
3934 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3942 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3950 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3951 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3952 int kflags, struct thread *td)
3958 struct fileops badfileops = {
3959 .fo_read = badfo_readwrite,
3960 .fo_write = badfo_readwrite,
3961 .fo_truncate = badfo_truncate,
3962 .fo_ioctl = badfo_ioctl,
3963 .fo_poll = badfo_poll,
3964 .fo_kqfilter = badfo_kqfilter,
3965 .fo_stat = badfo_stat,
3966 .fo_close = badfo_close,
3967 .fo_chmod = badfo_chmod,
3968 .fo_chown = badfo_chown,
3969 .fo_sendfile = badfo_sendfile,
3973 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3981 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3989 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3990 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3991 int kflags, struct thread *td)
3997 /*-------------------------------------------------------------------*/
4000 * File Descriptor pseudo-device driver (/dev/fd/).
4002 * Opening minor device N dup()s the file (if any) connected to file
4003 * descriptor N belonging to the calling process. Note that this driver
4004 * consists of only the ``open()'' routine, because all subsequent
4005 * references to this file will be direct to the other driver.
4007 * XXX: we could give this one a cloning event handler if necessary.
4012 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4016 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4017 * the file descriptor being sought for duplication. The error
4018 * return ensures that the vnode for this device will be released
4019 * by vn_open. Open will detect this special error and take the
4020 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4021 * will simply report the error.
4023 td->td_dupfd = dev2unit(dev);
4027 static struct cdevsw fildesc_cdevsw = {
4028 .d_version = D_VERSION,
4034 fildesc_drvinit(void *unused)
4038 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4039 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4040 make_dev_alias(dev, "stdin");
4041 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4042 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4043 make_dev_alias(dev, "stdout");
4044 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4045 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4046 make_dev_alias(dev, "stderr");
4049 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);