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"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/capsicum.h>
50 #include <sys/domain.h>
51 #include <sys/fcntl.h>
53 #include <sys/filedesc.h>
54 #include <sys/filio.h>
56 #include <sys/kernel.h>
58 #include <sys/limits.h>
60 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mqueue.h>
64 #include <sys/mutex.h>
65 #include <sys/namei.h>
66 #include <sys/selinfo.h>
70 #include <sys/procdesc.h>
71 #include <sys/protosw.h>
72 #include <sys/racct.h>
73 #include <sys/resourcevar.h>
75 #include <sys/signalvar.h>
76 #include <sys/socketvar.h>
79 #include <sys/syscallsubr.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysproto.h>
83 #include <sys/unistd.h>
85 #include <sys/unpcb.h>
87 #include <sys/vnode.h>
89 #include <sys/ktrace.h>
94 #include <netinet/in.h>
95 #include <netinet/in_pcb.h>
97 #include <security/audit/audit.h>
104 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
105 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
106 "file desc to leader structures");
107 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
108 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
110 MALLOC_DECLARE(M_FADVISE);
112 static uma_zone_t file_zone;
114 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
116 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
117 struct thread *td, int holdleaders);
118 static int fd_first_free(struct filedesc *fdp, int low, int size);
119 static int fd_last_used(struct filedesc *fdp, int size);
120 static void fdgrowtable(struct filedesc *fdp, int nfd);
121 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
122 static void fdunused(struct filedesc *fdp, int fd);
123 static void fdused(struct filedesc *fdp, int fd);
124 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
125 static int fill_procdesc_info(struct procdesc *pdp,
126 struct kinfo_file *kif);
127 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
128 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
129 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
130 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
131 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
132 static int getmaxfd(struct proc *p);
137 * - An array of open file descriptors (fd_ofiles)
138 * - An array of file flags (fd_ofileflags)
139 * - A bitmap recording which descriptors are in use (fd_map)
141 * A process starts out with NDFILE descriptors. The value of NDFILE has
142 * been selected based the historical limit of 20 open files, and an
143 * assumption that the majority of processes, especially short-lived
144 * processes like shells, will never need more.
146 * If this initial allocation is exhausted, a larger descriptor table and
147 * map are allocated dynamically, and the pointers in the process's struct
148 * filedesc are updated to point to those. This is repeated every time
149 * the process runs out of file descriptors (provided it hasn't hit its
152 * Since threads may hold references to individual descriptor table
153 * entries, the tables are never freed. Instead, they are placed on a
154 * linked list and freed only when the struct filedesc is released.
157 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
158 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
159 #define NDSLOT(x) ((x) / NDENTRIES)
160 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
161 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
164 * SLIST entry used to keep track of ofiles which must be reclaimed when
168 struct filedescent *ft_table;
169 SLIST_ENTRY(freetable) ft_next;
173 * Initial allocation: a filedesc structure + the head of SLIST used to
174 * keep track of old ofiles + enough space for NDFILE descriptors.
177 struct filedesc fd_fd;
178 SLIST_HEAD(, freetable) fd_free;
179 struct filedescent fd_dfiles[NDFILE];
180 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
184 * Descriptor management.
186 volatile int openfiles; /* actual number of open files */
187 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
188 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
190 /* A mutex to protect the association between a proc and filedesc. */
191 static struct mtx fdesc_mtx;
194 * If low >= size, just return low. Otherwise find the first zero bit in the
195 * given bitmap, starting at low and not exceeding size - 1. Return size if
199 fd_first_free(struct filedesc *fdp, int low, int size)
201 NDSLOTTYPE *map = fdp->fd_map;
209 if (low % NDENTRIES) {
210 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
211 if ((mask &= ~map[off]) != 0UL)
212 return (off * NDENTRIES + ffsl(mask) - 1);
215 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
216 if (map[off] != ~0UL)
217 return (off * NDENTRIES + ffsl(~map[off]) - 1);
222 * Find the highest non-zero bit in the given bitmap, starting at 0 and
223 * not exceeding size - 1. Return -1 if not found.
226 fd_last_used(struct filedesc *fdp, int size)
228 NDSLOTTYPE *map = fdp->fd_map;
233 if (size % NDENTRIES) {
234 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
235 if ((mask &= map[off]) != 0)
236 return (off * NDENTRIES + flsl(mask) - 1);
239 for (minoff = NDSLOT(0); off >= minoff; --off)
241 return (off * NDENTRIES + flsl(map[off]) - 1);
246 fdisused(struct filedesc *fdp, int fd)
249 FILEDESC_LOCK_ASSERT(fdp);
251 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
252 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
254 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
258 * Mark a file descriptor as used.
261 fdused(struct filedesc *fdp, int fd)
264 FILEDESC_XLOCK_ASSERT(fdp);
266 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
268 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
269 if (fd > fdp->fd_lastfile)
270 fdp->fd_lastfile = fd;
271 if (fd == fdp->fd_freefile)
272 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
276 * Mark a file descriptor as unused.
279 fdunused(struct filedesc *fdp, int fd)
282 FILEDESC_XLOCK_ASSERT(fdp);
284 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
285 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
286 ("fd=%d is still in use", fd));
288 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
289 if (fd < fdp->fd_freefile)
290 fdp->fd_freefile = fd;
291 if (fd == fdp->fd_lastfile)
292 fdp->fd_lastfile = fd_last_used(fdp, fd);
296 * Free a file descriptor.
299 fdfree(struct filedesc *fdp, int fd)
301 struct filedescent *fde;
303 fde = &fdp->fd_ofiles[fd];
304 filecaps_free(&fde->fde_caps);
305 bzero(fde, sizeof(*fde));
310 * System calls on descriptors.
312 #ifndef _SYS_SYSPROTO_H_
313 struct getdtablesize_args {
319 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
321 struct proc *p = td->td_proc;
326 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
327 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
329 if (lim < td->td_retval[0])
330 td->td_retval[0] = lim;
335 * Duplicate a file descriptor to a particular value.
337 * Note: keep in mind that a potential race condition exists when closing
338 * descriptors from a shared descriptor table (via rfork).
340 #ifndef _SYS_SYSPROTO_H_
348 sys_dup2(struct thread *td, struct dup2_args *uap)
351 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
356 * Duplicate a file descriptor.
358 #ifndef _SYS_SYSPROTO_H_
365 sys_dup(struct thread *td, struct dup_args *uap)
368 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
372 * The file control system call.
374 #ifndef _SYS_SYSPROTO_H_
383 sys_fcntl(struct thread *td, struct fcntl_args *uap)
398 * Convert old flock structure to new.
400 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
401 fl.l_start = ofl.l_start;
402 fl.l_len = ofl.l_len;
403 fl.l_pid = ofl.l_pid;
404 fl.l_type = ofl.l_type;
405 fl.l_whence = ofl.l_whence;
425 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
434 error = kern_fcntl(td, uap->fd, cmd, arg);
437 if (uap->cmd == F_OGETLK) {
438 ofl.l_start = fl.l_start;
439 ofl.l_len = fl.l_len;
440 ofl.l_pid = fl.l_pid;
441 ofl.l_type = fl.l_type;
442 ofl.l_whence = fl.l_whence;
443 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
444 } else if (uap->cmd == F_GETLK) {
445 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
451 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
453 struct filedesc *fdp;
455 struct file *fp, *fp2;
456 struct filedescent *fde;
473 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
476 case F_DUPFD_CLOEXEC:
478 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
484 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
487 case F_DUP2FD_CLOEXEC:
489 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
495 if ((fp = fget_locked(fdp, fd)) == NULL) {
496 FILEDESC_SUNLOCK(fdp);
500 fde = &fdp->fd_ofiles[fd];
502 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
503 FILEDESC_SUNLOCK(fdp);
508 if ((fp = fget_locked(fdp, fd)) == NULL) {
509 FILEDESC_XUNLOCK(fdp);
513 fde = &fdp->fd_ofiles[fd];
514 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
515 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
516 FILEDESC_XUNLOCK(fdp);
520 error = fget_unlocked(fdp, fd,
521 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp, NULL);
524 td->td_retval[0] = OFLAGS(fp->f_flag);
529 error = fget_unlocked(fdp, fd,
530 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp, NULL);
534 tmp = flg = fp->f_flag;
536 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
537 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
538 tmp = fp->f_flag & FNONBLOCK;
539 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
544 tmp = fp->f_flag & FASYNC;
545 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
550 atomic_clear_int(&fp->f_flag, FNONBLOCK);
552 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
557 error = fget_unlocked(fdp, fd,
558 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp, NULL);
561 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
563 td->td_retval[0] = tmp;
568 error = fget_unlocked(fdp, fd,
569 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp, NULL);
573 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
578 error = priv_check(td, PRIV_NFS_LOCKD);
586 /* FALLTHROUGH F_SETLK */
590 cap_rights_init(&rights, CAP_FLOCK);
591 error = fget_unlocked(fdp, fd, &rights, 0, &fp, NULL);
594 if (fp->f_type != DTYPE_VNODE) {
600 flp = (struct flock *)arg;
601 if (flp->l_whence == SEEK_CUR) {
602 foffset = foffset_get(fp);
605 foffset > OFF_MAX - flp->l_start)) {
606 FILEDESC_SUNLOCK(fdp);
611 flp->l_start += foffset;
615 switch (flp->l_type) {
617 if ((fp->f_flag & FREAD) == 0) {
621 PROC_LOCK(p->p_leader);
622 p->p_leader->p_flag |= P_ADVLOCK;
623 PROC_UNLOCK(p->p_leader);
624 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
628 if ((fp->f_flag & FWRITE) == 0) {
632 PROC_LOCK(p->p_leader);
633 p->p_leader->p_flag |= P_ADVLOCK;
634 PROC_UNLOCK(p->p_leader);
635 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
639 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
644 * Temporary api for testing remote lock
647 if (flg != F_REMOTE) {
651 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
652 F_UNLCKSYS, flp, flg);
658 if (error != 0 || flp->l_type == F_UNLCK ||
659 flp->l_type == F_UNLCKSYS) {
665 * Check for a race with close.
667 * The vnode is now advisory locked (or unlocked, but this case
668 * is not really important) as the caller requested.
669 * We had to drop the filedesc lock, so we need to recheck if
670 * the descriptor is still valid, because if it was closed
671 * in the meantime we need to remove advisory lock from the
672 * vnode - close on any descriptor leading to an advisory
673 * locked vnode, removes that lock.
674 * We will return 0 on purpose in that case, as the result of
675 * successful advisory lock might have been externally visible
676 * already. This is fine - effectively we pretend to the caller
677 * that the closing thread was a bit slower and that the
678 * advisory lock succeeded before the close.
680 error = fget_unlocked(fdp, fd, &rights, 0, &fp2, NULL);
686 flp->l_whence = SEEK_SET;
689 flp->l_type = F_UNLCK;
690 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
691 F_UNLCK, flp, F_POSIX);
698 error = fget_unlocked(fdp, fd,
699 cap_rights_init(&rights, CAP_FLOCK), 0, &fp, NULL);
702 if (fp->f_type != DTYPE_VNODE) {
707 flp = (struct flock *)arg;
708 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
709 flp->l_type != F_UNLCK) {
714 if (flp->l_whence == SEEK_CUR) {
715 foffset = foffset_get(fp);
716 if ((flp->l_start > 0 &&
717 foffset > OFF_MAX - flp->l_start) ||
719 foffset < OFF_MIN - flp->l_start)) {
720 FILEDESC_SUNLOCK(fdp);
725 flp->l_start += foffset;
728 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
734 arg = arg ? 128 * 1024: 0;
737 error = fget_unlocked(fdp, fd, NULL, 0, &fp, NULL);
740 if (fp->f_type != DTYPE_VNODE) {
747 error = vn_lock(vp, LK_SHARED);
752 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
754 fp->f_seqcount = (arg + bsize - 1) / bsize;
756 new = old = fp->f_flag;
758 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
761 new = old = fp->f_flag;
763 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
776 getmaxfd(struct proc *p)
781 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
788 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
791 do_dup(struct thread *td, int flags, int old, int new,
794 struct filedesc *fdp;
795 struct filedescent *oldfde, *newfde;
805 * Verify we have a valid descriptor to dup from and possibly to
806 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
807 * return EINVAL when the new descriptor is out of bounds.
812 return (flags & DUP_FCNTL ? EINVAL : EBADF);
815 return (flags & DUP_FCNTL ? EINVAL : EBADF);
818 if (fget_locked(fdp, old) == NULL) {
819 FILEDESC_XUNLOCK(fdp);
822 oldfde = &fdp->fd_ofiles[old];
823 if (flags & DUP_FIXED && old == new) {
825 if (flags & DUP_CLOEXEC)
826 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
827 FILEDESC_XUNLOCK(fdp);
830 fp = oldfde->fde_file;
834 * If the caller specified a file descriptor, make sure the file
835 * table is large enough to hold it, and grab it. Otherwise, just
836 * allocate a new descriptor the usual way.
838 if (flags & DUP_FIXED) {
839 if (new >= fdp->fd_nfiles) {
841 * The resource limits are here instead of e.g.
842 * fdalloc(), because the file descriptor table may be
843 * shared between processes, so we can't really use
844 * racct_add()/racct_sub(). Instead of counting the
845 * number of actually allocated descriptors, just put
846 * the limit on the size of the file descriptor table.
850 error = racct_set(p, RACCT_NOFILE, new + 1);
853 FILEDESC_XUNLOCK(fdp);
858 fdgrowtable_exp(fdp, new + 1);
859 oldfde = &fdp->fd_ofiles[old];
861 newfde = &fdp->fd_ofiles[new];
862 if (newfde->fde_file == NULL)
865 if ((error = fdalloc(td, new, &new)) != 0) {
866 FILEDESC_XUNLOCK(fdp);
870 newfde = &fdp->fd_ofiles[new];
873 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
874 KASSERT(old != new, ("new fd is same as old"));
876 delfp = newfde->fde_file;
879 * Duplicate the source descriptor.
881 filecaps_free(&newfde->fde_caps);
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. 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 /* copy the old data over and point at the new tables */
1533 memcpy(ntable, otable, onfiles * sizeof(*otable));
1534 fdp->fd_ofiles = ntable;
1537 * Allocate a new map only if the old is not large enough. It will
1538 * grow at a slower rate than the table as it can map more
1539 * entries than the table can hold.
1541 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1542 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1544 /* copy over the old data and update the pointer */
1545 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1550 * In order to have a valid pattern for fget_unlocked()
1551 * fdp->fd_nfiles must be the last member to be updated, otherwise
1552 * fget_unlocked() consumers may reference a new, higher value for
1553 * fdp->fd_nfiles before to access the fdp->fd_ofiles array,
1554 * resulting in OOB accesses.
1556 atomic_store_rel_int(&fdp->fd_nfiles, nnfiles);
1559 * Do not free the old file table, as some threads may still
1560 * reference entries within it. Instead, place it on a freelist
1561 * which will be processed when the struct filedesc is released.
1563 * Note that if onfiles == NDFILE, we're dealing with the original
1564 * static allocation contained within (struct filedesc0 *)fdp,
1565 * which must not be freed.
1567 if (onfiles > NDFILE) {
1568 ft = (struct freetable *)&otable[onfiles];
1569 fdp0 = (struct filedesc0 *)fdp;
1570 ft->ft_table = otable;
1571 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1574 * The map does not have the same possibility of threads still
1575 * holding references to it. So always free it as long as it
1576 * does not reference the original static allocation.
1578 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1579 free(omap, M_FILEDESC);
1583 * Allocate a file descriptor for the process.
1586 fdalloc(struct thread *td, int minfd, int *result)
1588 struct proc *p = td->td_proc;
1589 struct filedesc *fdp = p->p_fd;
1590 int fd = -1, maxfd, allocfd;
1595 FILEDESC_XLOCK_ASSERT(fdp);
1597 if (fdp->fd_freefile > minfd)
1598 minfd = fdp->fd_freefile;
1600 maxfd = getmaxfd(p);
1603 * Search the bitmap for a free descriptor starting at minfd.
1604 * If none is found, grow the file table.
1606 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1609 if (fd >= fdp->fd_nfiles) {
1610 allocfd = min(fd * 2, maxfd);
1613 error = racct_set(p, RACCT_NOFILE, allocfd);
1619 * fd is already equal to first free descriptor >= minfd, so
1620 * we only need to grow the table and we are done.
1622 fdgrowtable_exp(fdp, allocfd);
1626 * Perform some sanity checks, then mark the file descriptor as
1627 * used and return it to the caller.
1629 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1630 ("invalid descriptor %d", fd));
1631 KASSERT(!fdisused(fdp, fd),
1632 ("fd_first_free() returned non-free descriptor"));
1633 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1634 ("file descriptor isn't free"));
1635 KASSERT(fdp->fd_ofiles[fd].fde_flags == 0, ("file flags are set"));
1642 * Allocate n file descriptors for the process.
1645 fdallocn(struct thread *td, int minfd, int *fds, int n)
1647 struct proc *p = td->td_proc;
1648 struct filedesc *fdp = p->p_fd;
1651 FILEDESC_XLOCK_ASSERT(fdp);
1653 for (i = 0; i < n; i++)
1654 if (fdalloc(td, 0, &fds[i]) != 0)
1658 for (i--; i >= 0; i--)
1659 fdunused(fdp, fds[i]);
1667 * Create a new open file structure and allocate a file decriptor for the
1668 * process that refers to it. We add one reference to the file for the
1669 * descriptor table and one reference for resultfp. This is to prevent us
1670 * being preempted and the entry in the descriptor table closed after we
1671 * release the FILEDESC lock.
1674 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1679 error = falloc_noinstall(td, &fp);
1681 return (error); /* no reference held on error */
1683 error = finstall(td, fp, &fd, flags, NULL);
1685 fdrop(fp, td); /* one reference (fp only) */
1689 if (resultfp != NULL)
1690 *resultfp = fp; /* copy out result */
1692 fdrop(fp, td); /* release local reference */
1694 if (resultfd != NULL)
1701 * Create a new open file structure without allocating a file descriptor.
1704 falloc_noinstall(struct thread *td, struct file **resultfp)
1707 int maxuserfiles = maxfiles - (maxfiles / 20);
1708 static struct timeval lastfail;
1711 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1713 if ((openfiles >= maxuserfiles &&
1714 priv_check(td, PRIV_MAXFILES) != 0) ||
1715 openfiles >= maxfiles) {
1716 if (ppsratecheck(&lastfail, &curfail, 1)) {
1717 printf("kern.maxfiles limit exceeded by uid %i, "
1718 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1722 atomic_add_int(&openfiles, 1);
1723 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1724 refcount_init(&fp->f_count, 1);
1725 fp->f_cred = crhold(td->td_ucred);
1726 fp->f_ops = &badfileops;
1734 * Install a file in a file descriptor table.
1737 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1738 struct filecaps *fcaps)
1740 struct filedesc *fdp = td->td_proc->p_fd;
1741 struct filedescent *fde;
1744 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1745 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1747 filecaps_validate(fcaps, __func__);
1749 FILEDESC_XLOCK(fdp);
1750 if ((error = fdalloc(td, 0, fd))) {
1751 FILEDESC_XUNLOCK(fdp);
1755 fde = &fdp->fd_ofiles[*fd];
1757 if ((flags & O_CLOEXEC) != 0)
1758 fde->fde_flags |= UF_EXCLOSE;
1760 filecaps_move(fcaps, &fde->fde_caps);
1762 filecaps_fill(&fde->fde_caps);
1763 FILEDESC_XUNLOCK(fdp);
1768 * Build a new filedesc structure from another.
1769 * Copy the current, root, and jail root vnode references.
1772 fdinit(struct filedesc *fdp)
1774 struct filedesc0 *newfdp;
1776 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1777 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1779 FILEDESC_SLOCK(fdp);
1780 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1781 if (newfdp->fd_fd.fd_cdir)
1782 VREF(newfdp->fd_fd.fd_cdir);
1783 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1784 if (newfdp->fd_fd.fd_rdir)
1785 VREF(newfdp->fd_fd.fd_rdir);
1786 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1787 if (newfdp->fd_fd.fd_jdir)
1788 VREF(newfdp->fd_fd.fd_jdir);
1789 FILEDESC_SUNLOCK(fdp);
1792 /* Create the file descriptor table. */
1793 newfdp->fd_fd.fd_refcnt = 1;
1794 newfdp->fd_fd.fd_holdcnt = 1;
1795 newfdp->fd_fd.fd_cmask = CMASK;
1796 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1797 newfdp->fd_fd.fd_nfiles = NDFILE;
1798 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1799 newfdp->fd_fd.fd_lastfile = -1;
1800 return (&newfdp->fd_fd);
1803 static struct filedesc *
1804 fdhold(struct proc *p)
1806 struct filedesc *fdp;
1808 mtx_lock(&fdesc_mtx);
1812 mtx_unlock(&fdesc_mtx);
1817 fddrop(struct filedesc *fdp)
1819 struct filedesc0 *fdp0;
1820 struct freetable *ft;
1823 mtx_lock(&fdesc_mtx);
1824 i = --fdp->fd_holdcnt;
1825 mtx_unlock(&fdesc_mtx);
1829 FILEDESC_LOCK_DESTROY(fdp);
1830 fdp0 = (struct filedesc0 *)fdp;
1831 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1832 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1833 free(ft->ft_table, M_FILEDESC);
1835 free(fdp, M_FILEDESC);
1839 * Share a filedesc structure.
1842 fdshare(struct filedesc *fdp)
1845 FILEDESC_XLOCK(fdp);
1847 FILEDESC_XUNLOCK(fdp);
1852 * Unshare a filedesc structure, if necessary by making a copy
1855 fdunshare(struct proc *p, struct thread *td)
1858 FILEDESC_XLOCK(p->p_fd);
1859 if (p->p_fd->fd_refcnt > 1) {
1860 struct filedesc *tmp;
1862 FILEDESC_XUNLOCK(p->p_fd);
1863 tmp = fdcopy(p->p_fd);
1867 FILEDESC_XUNLOCK(p->p_fd);
1871 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1872 * this is to ease callers, not catch errors.
1875 fdcopy(struct filedesc *fdp)
1877 struct filedesc *newfdp;
1878 struct filedescent *nfde, *ofde;
1881 /* Certain daemons might not have file descriptors. */
1885 newfdp = fdinit(fdp);
1886 FILEDESC_SLOCK(fdp);
1887 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1888 FILEDESC_SUNLOCK(fdp);
1889 FILEDESC_XLOCK(newfdp);
1890 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1891 FILEDESC_XUNLOCK(newfdp);
1892 FILEDESC_SLOCK(fdp);
1894 /* copy all passable descriptors (i.e. not kqueue) */
1895 newfdp->fd_freefile = -1;
1896 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1897 ofde = &fdp->fd_ofiles[i];
1898 if (fdisused(fdp, i) &&
1899 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) &&
1900 ofde->fde_file->f_ops != &badfileops) {
1901 nfde = &newfdp->fd_ofiles[i];
1903 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1904 fhold(nfde->fde_file);
1905 newfdp->fd_lastfile = i;
1907 if (newfdp->fd_freefile == -1)
1908 newfdp->fd_freefile = i;
1911 newfdp->fd_cmask = fdp->fd_cmask;
1912 FILEDESC_SUNLOCK(fdp);
1913 FILEDESC_XLOCK(newfdp);
1914 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1915 if (newfdp->fd_ofiles[i].fde_file != NULL)
1918 if (newfdp->fd_freefile == -1)
1919 newfdp->fd_freefile = i;
1920 FILEDESC_XUNLOCK(newfdp);
1925 * Release a filedesc structure.
1928 fdescfree(struct thread *td)
1930 struct filedesc *fdp;
1932 struct filedesc_to_leader *fdtol;
1934 struct vnode *cdir, *jdir, *rdir, *vp;
1937 /* Certain daemons might not have file descriptors. */
1938 fdp = td->td_proc->p_fd;
1943 PROC_LOCK(td->td_proc);
1944 racct_set(td->td_proc, RACCT_NOFILE, 0);
1945 PROC_UNLOCK(td->td_proc);
1948 /* Check for special need to clear POSIX style locks */
1949 fdtol = td->td_proc->p_fdtol;
1950 if (fdtol != NULL) {
1951 FILEDESC_XLOCK(fdp);
1952 KASSERT(fdtol->fdl_refcount > 0,
1953 ("filedesc_to_refcount botch: fdl_refcount=%d",
1954 fdtol->fdl_refcount));
1955 if (fdtol->fdl_refcount == 1 &&
1956 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1957 for (i = 0; i <= fdp->fd_lastfile; i++) {
1958 fp = fdp->fd_ofiles[i].fde_file;
1959 if (fp == NULL || fp->f_type != DTYPE_VNODE)
1962 FILEDESC_XUNLOCK(fdp);
1963 lf.l_whence = SEEK_SET;
1966 lf.l_type = F_UNLCK;
1968 (void) VOP_ADVLOCK(vp,
1969 (caddr_t)td->td_proc->p_leader, F_UNLCK,
1971 FILEDESC_XLOCK(fdp);
1976 if (fdtol->fdl_refcount == 1) {
1977 if (fdp->fd_holdleaderscount > 0 &&
1978 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1980 * close() or do_dup() has cleared a reference
1981 * in a shared file descriptor table.
1983 fdp->fd_holdleaderswakeup = 1;
1984 sx_sleep(&fdp->fd_holdleaderscount,
1985 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1988 if (fdtol->fdl_holdcount > 0) {
1990 * Ensure that fdtol->fdl_leader remains
1991 * valid in closef().
1993 fdtol->fdl_wakeup = 1;
1994 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1999 fdtol->fdl_refcount--;
2000 if (fdtol->fdl_refcount == 0 &&
2001 fdtol->fdl_holdcount == 0) {
2002 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2003 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2006 td->td_proc->p_fdtol = NULL;
2007 FILEDESC_XUNLOCK(fdp);
2009 free(fdtol, M_FILEDESC_TO_LEADER);
2011 FILEDESC_XLOCK(fdp);
2012 i = --fdp->fd_refcnt;
2013 FILEDESC_XUNLOCK(fdp);
2017 for (i = 0; i <= fdp->fd_lastfile; i++) {
2018 fp = fdp->fd_ofiles[i].fde_file;
2020 FILEDESC_XLOCK(fdp);
2022 FILEDESC_XUNLOCK(fdp);
2023 (void) closef(fp, td);
2026 FILEDESC_XLOCK(fdp);
2028 /* XXX This should happen earlier. */
2029 mtx_lock(&fdesc_mtx);
2030 td->td_proc->p_fd = NULL;
2031 mtx_unlock(&fdesc_mtx);
2033 if (fdp->fd_nfiles > NDFILE)
2034 free(fdp->fd_ofiles, M_FILEDESC);
2035 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2036 free(fdp->fd_map, M_FILEDESC);
2040 cdir = fdp->fd_cdir;
2041 fdp->fd_cdir = NULL;
2042 rdir = fdp->fd_rdir;
2043 fdp->fd_rdir = NULL;
2044 jdir = fdp->fd_jdir;
2045 fdp->fd_jdir = NULL;
2046 FILEDESC_XUNLOCK(fdp);
2059 * For setugid programs, we don't want to people to use that setugidness
2060 * to generate error messages which write to a file which otherwise would
2061 * otherwise be off-limits to the process. We check for filesystems where
2062 * the vnode can change out from under us after execve (like [lin]procfs).
2064 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2065 * sufficient. We also don't check for setugidness since we know we are.
2068 is_unsafe(struct file *fp)
2070 if (fp->f_type == DTYPE_VNODE) {
2071 struct vnode *vp = fp->f_vnode;
2073 if ((vp->v_vflag & VV_PROCDEP) != 0)
2080 * Make this setguid thing safe, if at all possible.
2083 setugidsafety(struct thread *td)
2085 struct filedesc *fdp;
2089 /* Certain daemons might not have file descriptors. */
2090 fdp = td->td_proc->p_fd;
2095 * Note: fdp->fd_ofiles may be reallocated out from under us while
2096 * we are blocked in a close. Be careful!
2098 FILEDESC_XLOCK(fdp);
2099 for (i = 0; i <= fdp->fd_lastfile; i++) {
2102 fp = fdp->fd_ofiles[i].fde_file;
2103 if (fp != NULL && is_unsafe(fp)) {
2104 knote_fdclose(td, i);
2106 * NULL-out descriptor prior to close to avoid
2107 * a race while close blocks.
2110 FILEDESC_XUNLOCK(fdp);
2111 (void) closef(fp, td);
2112 FILEDESC_XLOCK(fdp);
2115 FILEDESC_XUNLOCK(fdp);
2119 * If a specific file object occupies a specific file descriptor, close the
2120 * file descriptor entry and drop a reference on the file object. This is a
2121 * convenience function to handle a subsequent error in a function that calls
2122 * falloc() that handles the race that another thread might have closed the
2123 * file descriptor out from under the thread creating the file object.
2126 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2129 FILEDESC_XLOCK(fdp);
2130 if (fdp->fd_ofiles[idx].fde_file == fp) {
2132 FILEDESC_XUNLOCK(fdp);
2135 FILEDESC_XUNLOCK(fdp);
2139 * Close any files on exec?
2142 fdcloseexec(struct thread *td)
2144 struct filedesc *fdp;
2145 struct filedescent *fde;
2149 /* Certain daemons might not have file descriptors. */
2150 fdp = td->td_proc->p_fd;
2155 * We cannot cache fd_ofiles since operations
2156 * may block and rip them out from under us.
2158 FILEDESC_XLOCK(fdp);
2159 for (i = 0; i <= fdp->fd_lastfile; i++) {
2160 fde = &fdp->fd_ofiles[i];
2162 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2163 (fde->fde_flags & UF_EXCLOSE))) {
2165 (void) closefp(fdp, i, fp, td, 0);
2166 /* closefp() drops the FILEDESC lock. */
2167 FILEDESC_XLOCK(fdp);
2170 FILEDESC_XUNLOCK(fdp);
2174 * It is unsafe for set[ug]id processes to be started with file
2175 * descriptors 0..2 closed, as these descriptors are given implicit
2176 * significance in the Standard C library. fdcheckstd() will create a
2177 * descriptor referencing /dev/null for each of stdin, stdout, and
2178 * stderr that is not already open.
2181 fdcheckstd(struct thread *td)
2183 struct filedesc *fdp;
2184 register_t retval, save;
2185 int i, error, devnull;
2187 fdp = td->td_proc->p_fd;
2190 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2193 for (i = 0; i < 3; i++) {
2194 if (fdp->fd_ofiles[i].fde_file != NULL)
2197 save = td->td_retval[0];
2198 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2200 devnull = td->td_retval[0];
2201 td->td_retval[0] = save;
2204 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2206 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2215 * Internal form of close. Decrement reference count on file structure.
2216 * Note: td may be NULL when closing a file that was being passed in a
2219 * XXXRW: Giant is not required for the caller, but often will be held; this
2220 * makes it moderately likely the Giant will be recursed in the VFS case.
2223 closef(struct file *fp, struct thread *td)
2227 struct filedesc_to_leader *fdtol;
2228 struct filedesc *fdp;
2231 * POSIX record locking dictates that any close releases ALL
2232 * locks owned by this process. This is handled by setting
2233 * a flag in the unlock to free ONLY locks obeying POSIX
2234 * semantics, and not to free BSD-style file locks.
2235 * If the descriptor was in a message, POSIX-style locks
2236 * aren't passed with the descriptor, and the thread pointer
2237 * will be NULL. Callers should be careful only to pass a
2238 * NULL thread pointer when there really is no owning
2239 * context that might have locks, or the locks will be
2242 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2244 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2245 lf.l_whence = SEEK_SET;
2248 lf.l_type = F_UNLCK;
2249 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2250 F_UNLCK, &lf, F_POSIX);
2252 fdtol = td->td_proc->p_fdtol;
2253 if (fdtol != NULL) {
2255 * Handle special case where file descriptor table is
2256 * shared between multiple process leaders.
2258 fdp = td->td_proc->p_fd;
2259 FILEDESC_XLOCK(fdp);
2260 for (fdtol = fdtol->fdl_next;
2261 fdtol != td->td_proc->p_fdtol;
2262 fdtol = fdtol->fdl_next) {
2263 if ((fdtol->fdl_leader->p_flag &
2266 fdtol->fdl_holdcount++;
2267 FILEDESC_XUNLOCK(fdp);
2268 lf.l_whence = SEEK_SET;
2271 lf.l_type = F_UNLCK;
2273 (void) VOP_ADVLOCK(vp,
2274 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2276 FILEDESC_XLOCK(fdp);
2277 fdtol->fdl_holdcount--;
2278 if (fdtol->fdl_holdcount == 0 &&
2279 fdtol->fdl_wakeup != 0) {
2280 fdtol->fdl_wakeup = 0;
2284 FILEDESC_XUNLOCK(fdp);
2287 return (fdrop(fp, td));
2291 * Initialize the file pointer with the specified properties.
2293 * The ops are set with release semantics to be certain that the flags, type,
2294 * and data are visible when ops is. This is to prevent ops methods from being
2295 * called with bad data.
2298 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2303 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2307 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2308 int needfcntl, struct file **fpp, cap_rights_t *haverightsp)
2313 cap_rights_t haverights;
2318 * Avoid reads reordering and then a first access to the
2319 * fdp->fd_ofiles table which could result in OOB operation.
2321 if (fd < 0 || fd >= atomic_load_acq_int(&fdp->fd_nfiles))
2324 * Fetch the descriptor locklessly. We avoid fdrop() races by
2325 * never raising a refcount above 0. To accomplish this we have
2326 * to use a cmpset loop rather than an atomic_add. The descriptor
2327 * must be re-verified once we acquire a reference to be certain
2328 * that the identity is still correct and we did not lose a race
2329 * due to preemption.
2332 fp = fdp->fd_ofiles[fd].fde_file;
2336 haverights = *cap_rights(fdp, fd);
2337 if (needrightsp != NULL) {
2338 error = cap_check(&haverights, needrightsp);
2341 if (cap_rights_is_set(needrightsp, CAP_FCNTL)) {
2342 error = cap_fcntl_check(fdp, fd, needfcntl);
2348 count = fp->f_count;
2352 * Use an acquire barrier to prevent caching of fd_ofiles
2353 * so it is refreshed for verification.
2355 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2357 if (fp == fdp->fd_ofiles[fd].fde_file)
2359 fdrop(fp, curthread);
2362 if (haverightsp != NULL) {
2364 *haverightsp = haverights;
2366 CAP_ALL(haverightsp);
2373 * Extract the file pointer associated with the specified descriptor for the
2374 * current user process.
2376 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2379 * File's rights will be checked against the capability rights mask.
2381 * If an error occured the non-zero error is returned and *fpp is set to
2382 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2383 * responsible for fdrop().
2386 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2387 cap_rights_t *needrightsp, u_char *maxprotp)
2389 struct filedesc *fdp;
2391 cap_rights_t haverights, needrights;
2395 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2397 if (needrightsp != NULL)
2398 needrights = *needrightsp;
2400 cap_rights_init(&needrights);
2401 if (maxprotp != NULL)
2402 cap_rights_set(&needrights, CAP_MMAP);
2403 error = fget_unlocked(fdp, fd, &needrights, 0, &fp, &haverights);
2406 if (fp->f_ops == &badfileops) {
2413 * If requested, convert capability rights to access flags.
2415 if (maxprotp != NULL)
2416 *maxprotp = cap_rights_to_vmprot(&haverights);
2417 #else /* !CAPABILITIES */
2418 if (maxprotp != NULL)
2419 *maxprotp = VM_PROT_ALL;
2420 #endif /* CAPABILITIES */
2423 * FREAD and FWRITE failure return EBADF as per POSIX.
2429 if ((fp->f_flag & flags) == 0)
2433 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2434 ((fp->f_flag & FWRITE) != 0))
2440 KASSERT(0, ("wrong flags"));
2453 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2456 return(_fget(td, fd, fpp, 0, rightsp, NULL));
2460 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2464 return (_fget(td, fd, fpp, 0, rightsp, maxprotp));
2468 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2471 return(_fget(td, fd, fpp, FREAD, rightsp, NULL));
2475 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2478 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2482 * Like fget() but loads the underlying vnode, or returns an error if the
2483 * descriptor does not represent a vnode. Note that pipes use vnodes but
2484 * never have VM objects. The returned vnode will be vref()'d.
2486 * XXX: what about the unused flags ?
2489 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2496 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2499 if (fp->f_vnode == NULL) {
2511 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2514 return (_fgetvp(td, fd, 0, rightsp, vpp));
2518 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2519 struct filecaps *havecaps, struct vnode **vpp)
2521 struct filedesc *fdp;
2527 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2530 fp = fget_locked(fdp, fd);
2531 if (fp == NULL || fp->f_ops == &badfileops)
2535 if (needrightsp != NULL) {
2536 error = cap_check(cap_rights(fdp, fd), needrightsp);
2542 if (fp->f_vnode == NULL)
2547 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2553 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2556 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2560 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2563 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2568 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2572 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2577 * Like fget() but loads the underlying socket, or returns an error if the
2578 * descriptor does not represent a socket.
2580 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2583 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2584 * on their file descriptor reference to prevent the socket from being free'd
2588 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2597 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2599 if (fp->f_type != DTYPE_SOCKET) {
2604 *fflagp = fp->f_flag;
2615 * Drop the reference count on the socket and XXX release the SX lock in the
2616 * future. The last reference closes the socket.
2618 * Note: fputsock() is deprecated, see comment for fgetsock().
2621 fputsock(struct socket *so)
2626 CURVNET_SET(so->so_vnet);
2632 * Handle the last reference to a file being closed.
2635 _fdrop(struct file *fp, struct thread *td)
2640 if (fp->f_count != 0)
2641 panic("fdrop: count %d", fp->f_count);
2642 if (fp->f_ops != &badfileops)
2643 error = fo_close(fp, td);
2644 atomic_subtract_int(&openfiles, 1);
2646 free(fp->f_advice, M_FADVISE);
2647 uma_zfree(file_zone, fp);
2653 * Apply an advisory lock on a file descriptor.
2655 * Just attempt to get a record lock of the requested type on the entire file
2656 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2658 #ifndef _SYS_SYSPROTO_H_
2666 sys_flock(struct thread *td, struct flock_args *uap)
2671 cap_rights_t rights;
2674 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2677 if (fp->f_type != DTYPE_VNODE) {
2679 return (EOPNOTSUPP);
2683 lf.l_whence = SEEK_SET;
2686 if (uap->how & LOCK_UN) {
2687 lf.l_type = F_UNLCK;
2688 atomic_clear_int(&fp->f_flag, FHASLOCK);
2689 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2692 if (uap->how & LOCK_EX)
2693 lf.l_type = F_WRLCK;
2694 else if (uap->how & LOCK_SH)
2695 lf.l_type = F_RDLCK;
2700 atomic_set_int(&fp->f_flag, FHASLOCK);
2701 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2702 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2708 * Duplicate the specified descriptor to a free descriptor.
2711 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2712 int openerror, int *indxp)
2717 KASSERT(openerror == ENODEV || openerror == ENXIO,
2718 ("unexpected error %d in %s", openerror, __func__));
2721 * If the to-be-dup'd fd number is greater than the allowed number
2722 * of file descriptors, or the fd to be dup'd has already been
2723 * closed, then reject.
2725 FILEDESC_XLOCK(fdp);
2726 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2727 FILEDESC_XUNLOCK(fdp);
2731 error = fdalloc(td, 0, &indx);
2733 FILEDESC_XUNLOCK(fdp);
2738 * There are two cases of interest here.
2740 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2742 * For ENXIO steal away the file structure from (dfd) and store it in
2743 * (indx). (dfd) is effectively closed by this operation.
2745 switch (openerror) {
2748 * Check that the mode the file is being opened for is a
2749 * subset of the mode of the existing descriptor.
2751 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2752 fdunused(fdp, indx);
2753 FILEDESC_XUNLOCK(fdp);
2757 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2758 filecaps_copy(&fdp->fd_ofiles[dfd].fde_caps,
2759 &fdp->fd_ofiles[indx].fde_caps);
2763 * Steal away the file pointer from dfd and stuff it into indx.
2765 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2766 bzero(&fdp->fd_ofiles[dfd], sizeof(fdp->fd_ofiles[dfd]));
2770 FILEDESC_XUNLOCK(fdp);
2776 * Scan all active processes and prisons to see if any of them have a current
2777 * or root directory of `olddp'. If so, replace them with the new mount point.
2780 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2782 struct filedesc *fdp;
2787 if (vrefcnt(olddp) == 1)
2790 sx_slock(&allproc_lock);
2791 FOREACH_PROC_IN_SYSTEM(p) {
2795 FILEDESC_XLOCK(fdp);
2796 if (fdp->fd_cdir == olddp) {
2798 fdp->fd_cdir = newdp;
2801 if (fdp->fd_rdir == olddp) {
2803 fdp->fd_rdir = newdp;
2806 if (fdp->fd_jdir == olddp) {
2808 fdp->fd_jdir = newdp;
2811 FILEDESC_XUNLOCK(fdp);
2814 sx_sunlock(&allproc_lock);
2815 if (rootvnode == olddp) {
2820 mtx_lock(&prison0.pr_mtx);
2821 if (prison0.pr_root == olddp) {
2823 prison0.pr_root = newdp;
2826 mtx_unlock(&prison0.pr_mtx);
2827 sx_slock(&allprison_lock);
2828 TAILQ_FOREACH(pr, &allprison, pr_list) {
2829 mtx_lock(&pr->pr_mtx);
2830 if (pr->pr_root == olddp) {
2832 pr->pr_root = newdp;
2835 mtx_unlock(&pr->pr_mtx);
2837 sx_sunlock(&allprison_lock);
2842 struct filedesc_to_leader *
2843 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2845 struct filedesc_to_leader *fdtol;
2847 fdtol = malloc(sizeof(struct filedesc_to_leader),
2848 M_FILEDESC_TO_LEADER,
2850 fdtol->fdl_refcount = 1;
2851 fdtol->fdl_holdcount = 0;
2852 fdtol->fdl_wakeup = 0;
2853 fdtol->fdl_leader = leader;
2855 FILEDESC_XLOCK(fdp);
2856 fdtol->fdl_next = old->fdl_next;
2857 fdtol->fdl_prev = old;
2858 old->fdl_next = fdtol;
2859 fdtol->fdl_next->fdl_prev = fdtol;
2860 FILEDESC_XUNLOCK(fdp);
2862 fdtol->fdl_next = fdtol;
2863 fdtol->fdl_prev = fdtol;
2869 * Get file structures globally.
2872 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2875 struct filedesc *fdp;
2880 error = sysctl_wire_old_buffer(req, 0);
2883 if (req->oldptr == NULL) {
2885 sx_slock(&allproc_lock);
2886 FOREACH_PROC_IN_SYSTEM(p) {
2887 if (p->p_state == PRS_NEW)
2892 /* overestimates sparse tables. */
2893 if (fdp->fd_lastfile > 0)
2894 n += fdp->fd_lastfile;
2897 sx_sunlock(&allproc_lock);
2898 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2901 bzero(&xf, sizeof(xf));
2902 xf.xf_size = sizeof(xf);
2903 sx_slock(&allproc_lock);
2904 FOREACH_PROC_IN_SYSTEM(p) {
2906 if (p->p_state == PRS_NEW) {
2910 if (p_cansee(req->td, p) != 0) {
2914 xf.xf_pid = p->p_pid;
2915 xf.xf_uid = p->p_ucred->cr_uid;
2920 FILEDESC_SLOCK(fdp);
2921 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2922 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
2926 xf.xf_data = fp->f_data;
2927 xf.xf_vnode = fp->f_vnode;
2928 xf.xf_type = fp->f_type;
2929 xf.xf_count = fp->f_count;
2931 xf.xf_offset = foffset_get(fp);
2932 xf.xf_flag = fp->f_flag;
2933 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2937 FILEDESC_SUNLOCK(fdp);
2942 sx_sunlock(&allproc_lock);
2946 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
2947 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2949 #ifdef KINFO_OFILE_SIZE
2950 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2953 #ifdef COMPAT_FREEBSD7
2955 export_vnode_for_osysctl(struct vnode *vp, int type,
2956 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2959 char *fullpath, *freepath;
2961 bzero(kif, sizeof(*kif));
2962 kif->kf_structsize = sizeof(*kif);
2966 kif->kf_type = KF_TYPE_VNODE;
2967 /* This function only handles directories. */
2968 if (vp->v_type != VDIR) {
2972 kif->kf_vnode_type = KF_VTYPE_VDIR;
2975 * This is not a true file descriptor, so we set a bogus refcount
2976 * and offset to indicate these fields should be ignored.
2978 kif->kf_ref_count = -1;
2979 kif->kf_offset = -1;
2983 FILEDESC_SUNLOCK(fdp);
2984 vn_fullpath(curthread, vp, &fullpath, &freepath);
2986 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2987 if (freepath != NULL)
2988 free(freepath, M_TEMP);
2989 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2990 FILEDESC_SLOCK(fdp);
2995 * Get per-process file descriptors for use by procstat(1), et al.
2998 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3000 char *fullpath, *freepath;
3001 struct kinfo_ofile *kif;
3002 struct filedesc *fdp;
3003 int error, i, *name;
3004 struct shmfd *shmfd;
3013 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3020 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3021 FILEDESC_SLOCK(fdp);
3022 if (fdp->fd_cdir != NULL)
3023 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3025 if (fdp->fd_rdir != NULL)
3026 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3028 if (fdp->fd_jdir != NULL)
3029 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3031 for (i = 0; fdp->fd_refcnt > 0 && i < fdp->fd_nfiles; i++) {
3032 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3034 bzero(kif, sizeof(*kif));
3035 kif->kf_structsize = sizeof(*kif);
3043 switch (fp->f_type) {
3045 kif->kf_type = KF_TYPE_VNODE;
3050 kif->kf_type = KF_TYPE_SOCKET;
3055 kif->kf_type = KF_TYPE_PIPE;
3059 kif->kf_type = KF_TYPE_FIFO;
3064 kif->kf_type = KF_TYPE_KQUEUE;
3068 kif->kf_type = KF_TYPE_CRYPTO;
3072 kif->kf_type = KF_TYPE_MQUEUE;
3076 kif->kf_type = KF_TYPE_SHM;
3081 kif->kf_type = KF_TYPE_SEM;
3086 kif->kf_type = KF_TYPE_PTS;
3090 case DTYPE_PROCDESC:
3091 kif->kf_type = KF_TYPE_PROCDESC;
3095 kif->kf_type = KF_TYPE_UNKNOWN;
3098 kif->kf_ref_count = fp->f_count;
3099 if (fp->f_flag & FREAD)
3100 kif->kf_flags |= KF_FLAG_READ;
3101 if (fp->f_flag & FWRITE)
3102 kif->kf_flags |= KF_FLAG_WRITE;
3103 if (fp->f_flag & FAPPEND)
3104 kif->kf_flags |= KF_FLAG_APPEND;
3105 if (fp->f_flag & FASYNC)
3106 kif->kf_flags |= KF_FLAG_ASYNC;
3107 if (fp->f_flag & FFSYNC)
3108 kif->kf_flags |= KF_FLAG_FSYNC;
3109 if (fp->f_flag & FNONBLOCK)
3110 kif->kf_flags |= KF_FLAG_NONBLOCK;
3111 if (fp->f_flag & O_DIRECT)
3112 kif->kf_flags |= KF_FLAG_DIRECT;
3113 if (fp->f_flag & FHASLOCK)
3114 kif->kf_flags |= KF_FLAG_HASLOCK;
3115 kif->kf_offset = foffset_get(fp);
3118 switch (vp->v_type) {
3120 kif->kf_vnode_type = KF_VTYPE_VNON;
3123 kif->kf_vnode_type = KF_VTYPE_VREG;
3126 kif->kf_vnode_type = KF_VTYPE_VDIR;
3129 kif->kf_vnode_type = KF_VTYPE_VBLK;
3132 kif->kf_vnode_type = KF_VTYPE_VCHR;
3135 kif->kf_vnode_type = KF_VTYPE_VLNK;
3138 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3141 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3144 kif->kf_vnode_type = KF_VTYPE_VBAD;
3147 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3151 * It is OK to drop the filedesc lock here as we will
3152 * re-validate and re-evaluate its properties when
3153 * the loop continues.
3157 FILEDESC_SUNLOCK(fdp);
3158 vn_fullpath(curthread, vp, &fullpath, &freepath);
3160 strlcpy(kif->kf_path, fullpath,
3161 sizeof(kif->kf_path));
3162 if (freepath != NULL)
3163 free(freepath, M_TEMP);
3164 FILEDESC_SLOCK(fdp);
3167 struct sockaddr *sa;
3169 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3170 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3171 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3174 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3175 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3176 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3179 kif->kf_sock_domain =
3180 so->so_proto->pr_domain->dom_family;
3181 kif->kf_sock_type = so->so_type;
3182 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3185 strlcpy(kif->kf_path, tty_devname(tp),
3186 sizeof(kif->kf_path));
3189 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3190 if (ks != NULL && ksem_info != NULL)
3191 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3192 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3196 FILEDESC_SUNLOCK(fdp);
3202 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3203 CTLFLAG_RD||CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3204 "Process ofiledesc entries");
3205 #endif /* COMPAT_FREEBSD7 */
3207 #ifdef KINFO_FILE_SIZE
3208 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3211 struct export_fd_buf {
3212 struct filedesc *fdp;
3215 struct kinfo_file kif;
3219 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3220 int64_t offset, cap_rights_t *rightsp, struct export_fd_buf *efbuf)
3225 } fflags_table[] = {
3226 { FAPPEND, KF_FLAG_APPEND },
3227 { FASYNC, KF_FLAG_ASYNC },
3228 { FFSYNC, KF_FLAG_FSYNC },
3229 { FHASLOCK, KF_FLAG_HASLOCK },
3230 { FNONBLOCK, KF_FLAG_NONBLOCK },
3231 { FREAD, KF_FLAG_READ },
3232 { FWRITE, KF_FLAG_WRITE },
3233 { O_CREAT, KF_FLAG_CREAT },
3234 { O_DIRECT, KF_FLAG_DIRECT },
3235 { O_EXCL, KF_FLAG_EXCL },
3236 { O_EXEC, KF_FLAG_EXEC },
3237 { O_EXLOCK, KF_FLAG_EXLOCK },
3238 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3239 { O_SHLOCK, KF_FLAG_SHLOCK },
3240 { O_TRUNC, KF_FLAG_TRUNC }
3242 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3243 struct kinfo_file *kif;
3248 if (efbuf->remainder == 0)
3251 bzero(kif, sizeof(*kif));
3252 locked = efbuf->fdp != NULL;
3257 FILEDESC_SUNLOCK(efbuf->fdp);
3260 vp = (struct vnode *)data;
3261 error = fill_vnode_info(vp, kif);
3264 case KF_TYPE_SOCKET:
3265 error = fill_socket_info((struct socket *)data, kif);
3268 error = fill_pipe_info((struct pipe *)data, kif);
3271 error = fill_pts_info((struct tty *)data, kif);
3273 case KF_TYPE_PROCDESC:
3274 error = fill_procdesc_info((struct procdesc *)data, kif);
3277 error = fill_sem_info((struct file *)data, kif);
3280 error = fill_shm_info((struct file *)data, kif);
3286 kif->kf_status |= KF_ATTR_VALID;
3289 * Translate file access flags.
3291 for (i = 0; i < NFFLAGS; i++)
3292 if (fflags & fflags_table[i].fflag)
3293 kif->kf_flags |= fflags_table[i].kf_fflag;
3294 if (rightsp != NULL)
3295 kif->kf_cap_rights = *rightsp;
3297 cap_rights_init(&kif->kf_cap_rights);
3299 kif->kf_type = type;
3300 kif->kf_ref_count = refcnt;
3301 kif->kf_offset = offset;
3302 /* Pack record size down */
3303 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3304 strlen(kif->kf_path) + 1;
3305 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3306 if (efbuf->remainder != -1) {
3307 if (efbuf->remainder < kif->kf_structsize) {
3308 /* Terminate export. */
3309 efbuf->remainder = 0;
3310 if (efbuf->fdp != NULL && !locked)
3311 FILEDESC_SLOCK(efbuf->fdp);
3314 efbuf->remainder -= kif->kf_structsize;
3317 FILEDESC_SUNLOCK(efbuf->fdp);
3318 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3319 if (efbuf->fdp != NULL)
3320 FILEDESC_SLOCK(efbuf->fdp);
3325 * Store a process file descriptor information to sbuf.
3327 * Takes a locked proc as argument, and returns with the proc unlocked.
3330 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3333 struct filedesc *fdp;
3334 struct export_fd_buf *efbuf;
3335 struct vnode *cttyvp, *textvp, *tracevp;
3339 int type, refcnt, fflags;
3340 cap_rights_t rights;
3342 PROC_LOCK_ASSERT(p, MA_OWNED);
3345 tracevp = p->p_tracevp;
3346 if (tracevp != NULL)
3349 textvp = p->p_textvp;
3352 /* Controlling tty. */
3354 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3355 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3361 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3364 efbuf->remainder = maxlen;
3365 if (tracevp != NULL)
3366 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3367 FREAD | FWRITE, -1, -1, NULL, efbuf);
3369 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3370 FREAD, -1, -1, NULL, efbuf);
3372 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3373 FREAD | FWRITE, -1, -1, NULL, efbuf);
3378 FILEDESC_SLOCK(fdp);
3379 /* working directory */
3380 if (fdp->fd_cdir != NULL) {
3382 data = fdp->fd_cdir;
3383 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3384 FREAD, -1, -1, NULL, efbuf);
3386 /* root directory */
3387 if (fdp->fd_rdir != NULL) {
3389 data = fdp->fd_rdir;
3390 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3391 FREAD, -1, -1, NULL, efbuf);
3393 /* jail directory */
3394 if (fdp->fd_jdir != NULL) {
3396 data = fdp->fd_jdir;
3397 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3398 FREAD, -1, -1, NULL, efbuf);
3400 for (i = 0; fdp->fd_refcnt > 0 && i < fdp->fd_nfiles; i++) {
3401 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3405 rights = *cap_rights(fdp, i);
3406 #else /* !CAPABILITIES */
3407 cap_rights_init(&rights);
3409 switch (fp->f_type) {
3411 type = KF_TYPE_VNODE;
3417 type = KF_TYPE_SOCKET;
3422 type = KF_TYPE_PIPE;
3427 type = KF_TYPE_FIFO;
3433 type = KF_TYPE_KQUEUE;
3437 type = KF_TYPE_CRYPTO;
3441 type = KF_TYPE_MQUEUE;
3459 case DTYPE_PROCDESC:
3460 type = KF_TYPE_PROCDESC;
3465 type = KF_TYPE_UNKNOWN;
3468 refcnt = fp->f_count;
3469 fflags = fp->f_flag;
3470 offset = foffset_get(fp);
3473 * Create sysctl entry.
3474 * It is OK to drop the filedesc lock here as we will
3475 * re-validate and re-evaluate its properties when
3476 * the loop continues.
3478 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3479 offset, &rights, efbuf);
3483 FILEDESC_SUNLOCK(fdp);
3486 free(efbuf, M_TEMP);
3490 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3493 * Get per-process file descriptors for use by procstat(1), et al.
3496 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3501 int error, error2, *name;
3505 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3506 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3511 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3512 error = kern_proc_filedesc_out(p, &sb, maxlen);
3513 error2 = sbuf_finish(&sb);
3515 return (error != 0 ? error : error2);
3519 vntype_to_kinfo(int vtype)
3524 } vtypes_table[] = {
3525 { VBAD, KF_VTYPE_VBAD },
3526 { VBLK, KF_VTYPE_VBLK },
3527 { VCHR, KF_VTYPE_VCHR },
3528 { VDIR, KF_VTYPE_VDIR },
3529 { VFIFO, KF_VTYPE_VFIFO },
3530 { VLNK, KF_VTYPE_VLNK },
3531 { VNON, KF_VTYPE_VNON },
3532 { VREG, KF_VTYPE_VREG },
3533 { VSOCK, KF_VTYPE_VSOCK }
3535 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3539 * Perform vtype translation.
3541 for (i = 0; i < NVTYPES; i++)
3542 if (vtypes_table[i].vtype == vtype)
3545 return (vtypes_table[i].kf_vtype);
3547 return (KF_VTYPE_UNKNOWN);
3551 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3554 char *fullpath, *freepath;
3559 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3562 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3564 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3566 if (freepath != NULL)
3567 free(freepath, M_TEMP);
3570 * Retrieve vnode attributes.
3572 va.va_fsid = VNOVAL;
3574 vn_lock(vp, LK_SHARED | LK_RETRY);
3575 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3579 if (va.va_fsid != VNOVAL)
3580 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3582 kif->kf_un.kf_file.kf_file_fsid =
3583 vp->v_mount->mnt_stat.f_fsid.val[0];
3584 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3585 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3586 kif->kf_un.kf_file.kf_file_size = va.va_size;
3587 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3592 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3594 struct sockaddr *sa;
3595 struct inpcb *inpcb;
3596 struct unpcb *unpcb;
3601 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3602 kif->kf_sock_type = so->so_type;
3603 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3604 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3605 switch(kif->kf_sock_domain) {
3608 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3609 if (so->so_pcb != NULL) {
3610 inpcb = (struct inpcb *)(so->so_pcb);
3611 kif->kf_un.kf_sock.kf_sock_inpcb =
3612 (uintptr_t)inpcb->inp_ppcb;
3617 if (so->so_pcb != NULL) {
3618 unpcb = (struct unpcb *)(so->so_pcb);
3619 if (unpcb->unp_conn) {
3620 kif->kf_un.kf_sock.kf_sock_unpconn =
3621 (uintptr_t)unpcb->unp_conn;
3622 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3623 so->so_rcv.sb_state;
3624 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3625 so->so_snd.sb_state;
3630 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3631 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3632 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3635 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3636 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3637 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3640 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3641 sizeof(kif->kf_path));
3646 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3651 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3652 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3657 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3662 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3663 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3664 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3669 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3674 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3679 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3685 if (fp->f_data == NULL)
3687 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3689 if (ksem_info == NULL)
3691 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3692 &kif->kf_un.kf_sem.kf_sem_value);
3693 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3698 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3704 if (fp->f_data == NULL)
3706 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3708 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3709 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3710 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3714 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3715 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3716 "Process filedesc entries");
3720 * For the purposes of debugging, generate a human-readable string for the
3724 file_type_to_name(short type)
3754 * For the purposes of debugging, identify a process (if any, perhaps one of
3755 * many) that references the passed file in its file descriptor array. Return
3758 static struct proc *
3759 file_to_first_proc(struct file *fp)
3761 struct filedesc *fdp;
3765 FOREACH_PROC_IN_SYSTEM(p) {
3766 if (p->p_state == PRS_NEW)
3771 for (n = 0; n < fdp->fd_nfiles; n++) {
3772 if (fp == fdp->fd_ofiles[n].fde_file)
3780 db_print_file(struct file *fp, int header)
3785 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3786 "File", "Type", "Data", "Flag", "GCFl", "Count",
3787 "MCount", "Vnode", "FPID", "FCmd");
3788 p = file_to_first_proc(fp);
3789 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3790 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3791 0, fp->f_count, 0, fp->f_vnode,
3792 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3795 DB_SHOW_COMMAND(file, db_show_file)
3800 db_printf("usage: show file <addr>\n");
3803 fp = (struct file *)addr;
3804 db_print_file(fp, 1);
3807 DB_SHOW_COMMAND(files, db_show_files)
3809 struct filedesc *fdp;
3816 FOREACH_PROC_IN_SYSTEM(p) {
3817 if (p->p_state == PRS_NEW)
3819 if ((fdp = p->p_fd) == NULL)
3821 for (n = 0; n < fdp->fd_nfiles; ++n) {
3822 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3824 db_print_file(fp, header);
3831 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3832 &maxfilesperproc, 0, "Maximum files allowed open per process");
3834 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3835 &maxfiles, 0, "Maximum number of files");
3837 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3838 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3842 filelistinit(void *dummy)
3845 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3846 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3847 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3848 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3850 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3852 /*-------------------------------------------------------------------*/
3855 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3856 int flags, struct thread *td)
3863 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3871 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3879 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3887 badfo_kqfilter(struct file *fp, struct knote *kn)
3894 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3902 badfo_close(struct file *fp, struct thread *td)
3909 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3917 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3925 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3926 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3927 int kflags, struct sendfile_sync *sfs, struct thread *td)
3933 struct fileops badfileops = {
3934 .fo_read = badfo_readwrite,
3935 .fo_write = badfo_readwrite,
3936 .fo_truncate = badfo_truncate,
3937 .fo_ioctl = badfo_ioctl,
3938 .fo_poll = badfo_poll,
3939 .fo_kqfilter = badfo_kqfilter,
3940 .fo_stat = badfo_stat,
3941 .fo_close = badfo_close,
3942 .fo_chmod = badfo_chmod,
3943 .fo_chown = badfo_chown,
3944 .fo_sendfile = badfo_sendfile,
3948 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3956 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3964 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3965 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3966 int kflags, struct sendfile_sync *sfs, struct thread *td)
3972 /*-------------------------------------------------------------------*/
3975 * File Descriptor pseudo-device driver (/dev/fd/).
3977 * Opening minor device N dup()s the file (if any) connected to file
3978 * descriptor N belonging to the calling process. Note that this driver
3979 * consists of only the ``open()'' routine, because all subsequent
3980 * references to this file will be direct to the other driver.
3982 * XXX: we could give this one a cloning event handler if necessary.
3987 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3991 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3992 * the file descriptor being sought for duplication. The error
3993 * return ensures that the vnode for this device will be released
3994 * by vn_open. Open will detect this special error and take the
3995 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3996 * will simply report the error.
3998 td->td_dupfd = dev2unit(dev);
4002 static struct cdevsw fildesc_cdevsw = {
4003 .d_version = D_VERSION,
4009 fildesc_drvinit(void *unused)
4013 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4014 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4015 make_dev_alias(dev, "stdin");
4016 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4017 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4018 make_dev_alias(dev, "stdout");
4019 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4020 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4021 make_dev_alias(dev, "stderr");
4024 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);