2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_capsicum.h"
41 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44 #include "opt_procdesc.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/capability.h>
51 #include <sys/domain.h>
52 #include <sys/fcntl.h>
54 #include <sys/filedesc.h>
55 #include <sys/filio.h>
57 #include <sys/kernel.h>
59 #include <sys/limits.h>
61 #include <sys/malloc.h>
63 #include <sys/mount.h>
64 #include <sys/mqueue.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/selinfo.h>
71 #include <sys/procdesc.h>
72 #include <sys/protosw.h>
73 #include <sys/racct.h>
74 #include <sys/resourcevar.h>
76 #include <sys/signalvar.h>
77 #include <sys/socketvar.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysctl.h>
82 #include <sys/sysproto.h>
84 #include <sys/unistd.h>
86 #include <sys/unpcb.h>
88 #include <sys/vnode.h>
90 #include <sys/ktrace.h>
95 #include <netinet/in.h>
96 #include <netinet/in_pcb.h>
98 #include <security/audit/audit.h>
105 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
106 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
107 "file desc to leader structures");
108 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
110 MALLOC_DECLARE(M_FADVISE);
112 static uma_zone_t file_zone;
114 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
116 /* Flags for do_dup() */
117 #define DUP_FIXED 0x1 /* Force fixed allocation */
118 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
119 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
121 static int do_dup(struct thread *td, int flags, int old, int new,
123 static int fd_first_free(struct filedesc *, int, int);
124 static int fd_last_used(struct filedesc *, int, int);
125 static void fdgrowtable(struct filedesc *, int);
126 static void fdunused(struct filedesc *fdp, int fd);
127 static void fdused(struct filedesc *fdp, int fd);
128 static int fill_vnode_info(struct vnode *vp, struct kinfo_file *kif);
129 static int fill_socket_info(struct socket *so, struct kinfo_file *kif);
130 static int fill_pts_info(struct tty *tp, struct kinfo_file *kif);
131 static int fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
132 static int fill_procdesc_info(struct procdesc *pdp,
133 struct kinfo_file *kif);
134 static int fill_sem_info(struct file *fp, struct kinfo_file *kif);
135 static int fill_shm_info(struct file *fp, struct kinfo_file *kif);
138 * A process is initially started out with NDFILE descriptors stored within
139 * this structure, selected to be enough for typical applications based on
140 * the historical limit of 20 open files (and the usage of descriptors by
141 * shells). If these descriptors are exhausted, a larger descriptor table
142 * may be allocated, up to a process' resource limit; the internal arrays
146 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
147 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
148 #define NDSLOT(x) ((x) / NDENTRIES)
149 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
150 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
153 * Storage required per open file descriptor.
155 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
158 * Storage to hold unused ofiles that need to be reclaimed.
161 struct file **ft_table;
162 SLIST_ENTRY(freetable) ft_next;
166 * Basic allocation of descriptors:
167 * one of the above, plus arrays for NDFILE descriptors.
170 struct filedesc fd_fd;
172 * ofiles which need to be reclaimed on free.
174 SLIST_HEAD(,freetable) fd_free;
176 * These arrays are used when the number of open files is
177 * <= NDFILE, and are then pointed to by the pointers above.
179 struct file *fd_dfiles[NDFILE];
180 char fd_dfileflags[NDFILE];
181 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
185 * Descriptor management.
187 volatile int openfiles; /* actual number of open files */
188 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
189 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
191 /* A mutex to protect the association between a proc and filedesc. */
192 static struct mtx fdesc_mtx;
195 * Find the first zero bit in the given bitmap, starting at low and not
196 * exceeding size - 1.
199 fd_first_free(struct filedesc *fdp, int low, int size)
201 NDSLOTTYPE *map = fdp->fd_map;
209 if (low % NDENTRIES) {
210 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
211 if ((mask &= ~map[off]) != 0UL)
212 return (off * NDENTRIES + ffsl(mask) - 1);
215 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
216 if (map[off] != ~0UL)
217 return (off * NDENTRIES + ffsl(~map[off]) - 1);
222 * Find the highest non-zero bit in the given bitmap, starting at low and
223 * not exceeding size - 1.
226 fd_last_used(struct filedesc *fdp, int low, int size)
228 NDSLOTTYPE *map = fdp->fd_map;
236 if (size % NDENTRIES) {
237 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
238 if ((mask &= map[off]) != 0)
239 return (off * NDENTRIES + flsl(mask) - 1);
242 for (minoff = NDSLOT(low); off >= minoff; --off)
244 return (off * NDENTRIES + flsl(map[off]) - 1);
249 fdisused(struct filedesc *fdp, int fd)
251 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
252 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
253 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
257 * Mark a file descriptor as used.
260 fdused(struct filedesc *fdp, int fd)
263 FILEDESC_XLOCK_ASSERT(fdp);
264 KASSERT(!fdisused(fdp, fd),
265 ("fd already used"));
267 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
268 if (fd > fdp->fd_lastfile)
269 fdp->fd_lastfile = fd;
270 if (fd == fdp->fd_freefile)
271 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
275 * Mark a file descriptor as unused.
278 fdunused(struct filedesc *fdp, int fd)
281 FILEDESC_XLOCK_ASSERT(fdp);
282 KASSERT(fdisused(fdp, fd),
283 ("fd is already unused"));
284 KASSERT(fdp->fd_ofiles[fd] == NULL,
285 ("fd is still in use"));
287 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
288 if (fd < fdp->fd_freefile)
289 fdp->fd_freefile = fd;
290 if (fd == fdp->fd_lastfile)
291 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
295 * System calls on descriptors.
297 #ifndef _SYS_SYSPROTO_H_
298 struct getdtablesize_args {
304 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
306 struct proc *p = td->td_proc;
311 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
312 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
314 if (lim < td->td_retval[0])
315 td->td_retval[0] = lim;
320 * Duplicate a file descriptor to a particular value.
322 * Note: keep in mind that a potential race condition exists when closing
323 * descriptors from a shared descriptor table (via rfork).
325 #ifndef _SYS_SYSPROTO_H_
333 sys_dup2(struct thread *td, struct dup2_args *uap)
336 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
341 * Duplicate a file descriptor.
343 #ifndef _SYS_SYSPROTO_H_
350 sys_dup(struct thread *td, struct dup_args *uap)
353 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
357 * The file control system call.
359 #ifndef _SYS_SYSPROTO_H_
368 sys_fcntl(struct thread *td, struct fcntl_args *uap)
383 * Convert old flock structure to new.
385 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
386 fl.l_start = ofl.l_start;
387 fl.l_len = ofl.l_len;
388 fl.l_pid = ofl.l_pid;
389 fl.l_type = ofl.l_type;
390 fl.l_whence = ofl.l_whence;
410 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
419 error = kern_fcntl(td, uap->fd, cmd, arg);
422 if (uap->cmd == F_OGETLK) {
423 ofl.l_start = fl.l_start;
424 ofl.l_len = fl.l_len;
425 ofl.l_pid = fl.l_pid;
426 ofl.l_type = fl.l_type;
427 ofl.l_whence = fl.l_whence;
428 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
429 } else if (uap->cmd == F_GETLK) {
430 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
435 static inline struct file *
436 fdtofp(int fd, struct filedesc *fdp)
440 FILEDESC_LOCK_ASSERT(fdp);
441 if ((unsigned)fd >= fdp->fd_nfiles ||
442 (fp = fdp->fd_ofiles[fd]) == NULL)
448 fdunwrap(int fd, cap_rights_t rights, struct filedesc *fdp, struct file **fpp)
451 *fpp = fdtofp(fd, fdp);
456 if ((*fpp)->f_type == DTYPE_CAPABILITY) {
457 int err = cap_funwrap(*fpp, rights, fpp);
463 #endif /* CAPABILITIES */
468 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
470 struct filedesc *fdp;
491 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
494 case F_DUPFD_CLOEXEC:
496 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
502 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
505 case F_DUP2FD_CLOEXEC:
507 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
513 if ((fp = fdtofp(fd, fdp)) == NULL) {
514 FILEDESC_SUNLOCK(fdp);
518 pop = &fdp->fd_ofileflags[fd];
519 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
520 FILEDESC_SUNLOCK(fdp);
525 if ((fp = fdtofp(fd, fdp)) == NULL) {
526 FILEDESC_XUNLOCK(fdp);
530 pop = &fdp->fd_ofileflags[fd];
531 *pop = (*pop &~ UF_EXCLOSE) |
532 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
533 FILEDESC_XUNLOCK(fdp);
538 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
540 FILEDESC_SUNLOCK(fdp);
543 td->td_retval[0] = OFLAGS(fp->f_flag);
544 FILEDESC_SUNLOCK(fdp);
549 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
551 FILEDESC_SUNLOCK(fdp);
555 FILEDESC_SUNLOCK(fdp);
557 tmp = flg = fp->f_flag;
559 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
560 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
561 tmp = fp->f_flag & FNONBLOCK;
562 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
567 tmp = fp->f_flag & FASYNC;
568 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
573 atomic_clear_int(&fp->f_flag, FNONBLOCK);
575 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
581 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
583 FILEDESC_SUNLOCK(fdp);
587 FILEDESC_SUNLOCK(fdp);
588 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
590 td->td_retval[0] = tmp;
596 error = fdunwrap(fd, CAP_FCNTL, fdp, &fp);
598 FILEDESC_SUNLOCK(fdp);
602 FILEDESC_SUNLOCK(fdp);
604 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
609 error = priv_check(td, PRIV_NFS_LOCKD);
617 /* FALLTHROUGH F_SETLK */
622 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
624 FILEDESC_SUNLOCK(fdp);
627 if (fp->f_type != DTYPE_VNODE) {
628 FILEDESC_SUNLOCK(fdp);
632 flp = (struct flock *)arg;
633 if (flp->l_whence == SEEK_CUR) {
634 foffset = foffset_get(fp);
637 foffset > OFF_MAX - flp->l_start)) {
638 FILEDESC_SUNLOCK(fdp);
642 flp->l_start += foffset;
646 * VOP_ADVLOCK() may block.
649 FILEDESC_SUNLOCK(fdp);
651 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
652 switch (flp->l_type) {
654 if ((fp->f_flag & FREAD) == 0) {
658 PROC_LOCK(p->p_leader);
659 p->p_leader->p_flag |= P_ADVLOCK;
660 PROC_UNLOCK(p->p_leader);
661 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
665 if ((fp->f_flag & FWRITE) == 0) {
669 PROC_LOCK(p->p_leader);
670 p->p_leader->p_flag |= P_ADVLOCK;
671 PROC_UNLOCK(p->p_leader);
672 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
676 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
681 * Temporary api for testing remote lock
684 if (flg != F_REMOTE) {
688 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
689 F_UNLCKSYS, flp, flg);
695 VFS_UNLOCK_GIANT(vfslocked);
697 /* Check for race with close */
699 if ((unsigned) fd >= fdp->fd_nfiles ||
700 fp != fdp->fd_ofiles[fd]) {
701 FILEDESC_SUNLOCK(fdp);
702 flp->l_whence = SEEK_SET;
705 flp->l_type = F_UNLCK;
706 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
707 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
708 F_UNLCK, flp, F_POSIX);
709 VFS_UNLOCK_GIANT(vfslocked);
712 FILEDESC_SUNLOCK(fdp);
718 error = fdunwrap(fd, CAP_FLOCK, fdp, &fp);
720 FILEDESC_SUNLOCK(fdp);
723 if (fp->f_type != DTYPE_VNODE) {
724 FILEDESC_SUNLOCK(fdp);
728 flp = (struct flock *)arg;
729 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
730 flp->l_type != F_UNLCK) {
731 FILEDESC_SUNLOCK(fdp);
735 if (flp->l_whence == SEEK_CUR) {
736 foffset = foffset_get(fp);
737 if ((flp->l_start > 0 &&
738 foffset > OFF_MAX - flp->l_start) ||
740 foffset < OFF_MIN - flp->l_start)) {
741 FILEDESC_SUNLOCK(fdp);
745 flp->l_start += foffset;
748 * VOP_ADVLOCK() may block.
751 FILEDESC_SUNLOCK(fdp);
753 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
754 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
756 VFS_UNLOCK_GIANT(vfslocked);
762 arg = arg ? 128 * 1024: 0;
766 if ((fp = fdtofp(fd, fdp)) == NULL) {
767 FILEDESC_SUNLOCK(fdp);
771 if (fp->f_type != DTYPE_VNODE) {
772 FILEDESC_SUNLOCK(fdp);
777 FILEDESC_SUNLOCK(fdp);
780 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
781 error = vn_lock(vp, LK_SHARED);
783 goto readahead_vnlock_fail;
784 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
786 fp->f_seqcount = (arg + bsize - 1) / bsize;
788 new = old = fp->f_flag;
790 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
791 readahead_vnlock_fail:
792 VFS_UNLOCK_GIANT(vfslocked);
796 new = old = fp->f_flag;
798 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
807 VFS_UNLOCK_GIANT(vfslocked);
812 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
815 do_dup(struct thread *td, int flags, int old, int new,
818 struct filedesc *fdp;
822 int error, holdleaders, maxfd;
828 * Verify we have a valid descriptor to dup from and possibly to
829 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
830 * return EINVAL when the new descriptor is out of bounds.
835 return (flags & DUP_FCNTL ? EINVAL : EBADF);
837 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
840 return (flags & DUP_FCNTL ? EINVAL : EBADF);
843 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
844 FILEDESC_XUNLOCK(fdp);
847 if (flags & DUP_FIXED && old == new) {
849 if (flags & DUP_CLOEXEC)
850 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
851 FILEDESC_XUNLOCK(fdp);
854 fp = fdp->fd_ofiles[old];
858 * If the caller specified a file descriptor, make sure the file
859 * table is large enough to hold it, and grab it. Otherwise, just
860 * allocate a new descriptor the usual way. Since the filedesc
861 * lock may be temporarily dropped in the process, we have to look
864 if (flags & DUP_FIXED) {
865 if (new >= fdp->fd_nfiles) {
867 * The resource limits are here instead of e.g.
868 * fdalloc(), because the file descriptor table may be
869 * shared between processes, so we can't really use
870 * racct_add()/racct_sub(). Instead of counting the
871 * number of actually allocated descriptors, just put
872 * the limit on the size of the file descriptor table.
876 error = racct_set(p, RACCT_NOFILE, new + 1);
879 FILEDESC_XUNLOCK(fdp);
884 fdgrowtable(fdp, new + 1);
886 if (fdp->fd_ofiles[new] == NULL)
889 if ((error = fdalloc(td, new, &new)) != 0) {
890 FILEDESC_XUNLOCK(fdp);
897 * If the old file changed out from under us then treat it as a
898 * bad file descriptor. Userland should do its own locking to
901 if (fdp->fd_ofiles[old] != fp) {
902 /* we've allocated a descriptor which we won't use */
903 if (fdp->fd_ofiles[new] == NULL)
905 FILEDESC_XUNLOCK(fdp);
910 ("new fd is same as old"));
913 * Save info on the descriptor being overwritten. We cannot close
914 * it without introducing an ownership race for the slot, since we
915 * need to drop the filedesc lock to call closef().
917 * XXX this duplicates parts of close().
919 delfp = fdp->fd_ofiles[new];
922 if (td->td_proc->p_fdtol != NULL) {
924 * Ask fdfree() to sleep to ensure that all relevant
925 * process leaders can be traversed in closef().
927 fdp->fd_holdleaderscount++;
933 * Duplicate the source descriptor
935 fdp->fd_ofiles[new] = fp;
936 if ((flags & DUP_CLOEXEC) != 0)
937 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
939 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
940 if (new > fdp->fd_lastfile)
941 fdp->fd_lastfile = new;
945 * If we dup'd over a valid file, we now own the reference to it
946 * and must dispose of it using closef() semantics (as if a
947 * close() were performed on it).
949 * XXX this duplicates parts of close().
952 knote_fdclose(td, new);
953 if (delfp->f_type == DTYPE_MQUEUE)
954 mq_fdclose(td, new, delfp);
955 FILEDESC_XUNLOCK(fdp);
956 (void) closef(delfp, td);
959 fdp->fd_holdleaderscount--;
960 if (fdp->fd_holdleaderscount == 0 &&
961 fdp->fd_holdleaderswakeup != 0) {
962 fdp->fd_holdleaderswakeup = 0;
963 wakeup(&fdp->fd_holdleaderscount);
965 FILEDESC_XUNLOCK(fdp);
968 FILEDESC_XUNLOCK(fdp);
974 * If sigio is on the list associated with a process or process group,
975 * disable signalling from the device, remove sigio from the list and
979 funsetown(struct sigio **sigiop)
989 *(sigio->sio_myref) = NULL;
990 if ((sigio)->sio_pgid < 0) {
991 struct pgrp *pg = (sigio)->sio_pgrp;
993 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
997 struct proc *p = (sigio)->sio_proc;
999 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
1000 sigio, sio_pgsigio);
1004 crfree(sigio->sio_ucred);
1005 free(sigio, M_SIGIO);
1009 * Free a list of sigio structures.
1010 * We only need to lock the SIGIO_LOCK because we have made ourselves
1011 * inaccessible to callers of fsetown and therefore do not need to lock
1012 * the proc or pgrp struct for the list manipulation.
1015 funsetownlst(struct sigiolst *sigiolst)
1019 struct sigio *sigio;
1021 sigio = SLIST_FIRST(sigiolst);
1028 * Every entry of the list should belong
1029 * to a single proc or pgrp.
1031 if (sigio->sio_pgid < 0) {
1032 pg = sigio->sio_pgrp;
1033 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
1034 } else /* if (sigio->sio_pgid > 0) */ {
1035 p = sigio->sio_proc;
1036 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1040 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
1041 *(sigio->sio_myref) = NULL;
1043 KASSERT(sigio->sio_pgid < 0,
1044 ("Proc sigio in pgrp sigio list"));
1045 KASSERT(sigio->sio_pgrp == pg,
1046 ("Bogus pgrp in sigio list"));
1048 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
1051 } else /* if (p != NULL) */ {
1052 KASSERT(sigio->sio_pgid > 0,
1053 ("Pgrp sigio in proc sigio list"));
1054 KASSERT(sigio->sio_proc == p,
1055 ("Bogus proc in sigio list"));
1057 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1062 crfree(sigio->sio_ucred);
1063 free(sigio, M_SIGIO);
1070 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1072 * After permission checking, add a sigio structure to the sigio list for
1073 * the process or process group.
1076 fsetown(pid_t pgid, struct sigio **sigiop)
1080 struct sigio *sigio;
1090 /* Allocate and fill in the new sigio out of locks. */
1091 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1092 sigio->sio_pgid = pgid;
1093 sigio->sio_ucred = crhold(curthread->td_ucred);
1094 sigio->sio_myref = sigiop;
1096 sx_slock(&proctree_lock);
1105 * Policy - Don't allow a process to FSETOWN a process
1106 * in another session.
1108 * Remove this test to allow maximum flexibility or
1109 * restrict FSETOWN to the current process or process
1110 * group for maximum safety.
1113 if (proc->p_session != curthread->td_proc->p_session) {
1119 } else /* if (pgid < 0) */ {
1120 pgrp = pgfind(-pgid);
1128 * Policy - Don't allow a process to FSETOWN a process
1129 * in another session.
1131 * Remove this test to allow maximum flexibility or
1132 * restrict FSETOWN to the current process or process
1133 * group for maximum safety.
1135 if (pgrp->pg_session != curthread->td_proc->p_session) {
1146 * Since funsetownlst() is called without the proctree
1147 * locked, we need to check for P_WEXIT.
1148 * XXX: is ESRCH correct?
1150 if ((proc->p_flag & P_WEXIT) != 0) {
1155 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1156 sigio->sio_proc = proc;
1160 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1161 sigio->sio_pgrp = pgrp;
1164 sx_sunlock(&proctree_lock);
1171 sx_sunlock(&proctree_lock);
1172 crfree(sigio->sio_ucred);
1173 free(sigio, M_SIGIO);
1178 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1182 struct sigio **sigiop;
1187 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1193 * Close a file descriptor.
1195 #ifndef _SYS_SYSPROTO_H_
1204 struct close_args *uap;
1207 return (kern_close(td, uap->fd));
1215 struct filedesc *fdp;
1216 struct file *fp, *fp_object;
1222 fdp = td->td_proc->p_fd;
1224 AUDIT_SYSCLOSE(td, fd);
1226 FILEDESC_XLOCK(fdp);
1227 if ((unsigned)fd >= fdp->fd_nfiles ||
1228 (fp = fdp->fd_ofiles[fd]) == NULL) {
1229 FILEDESC_XUNLOCK(fdp);
1232 fdp->fd_ofiles[fd] = NULL;
1233 fdp->fd_ofileflags[fd] = 0;
1235 if (td->td_proc->p_fdtol != NULL) {
1237 * Ask fdfree() to sleep to ensure that all relevant
1238 * process leaders can be traversed in closef().
1240 fdp->fd_holdleaderscount++;
1245 * We now hold the fp reference that used to be owned by the
1246 * descriptor array. We have to unlock the FILEDESC *AFTER*
1247 * knote_fdclose to prevent a race of the fd getting opened, a knote
1248 * added, and deleteing a knote for the new fd.
1250 knote_fdclose(td, fd);
1253 * When we're closing an fd with a capability, we need to notify
1254 * mqueue if the underlying object is of type mqueue.
1256 (void)cap_funwrap(fp, 0, &fp_object);
1257 if (fp_object->f_type == DTYPE_MQUEUE)
1258 mq_fdclose(td, fd, fp_object);
1259 FILEDESC_XUNLOCK(fdp);
1261 error = closef(fp, td);
1263 FILEDESC_XLOCK(fdp);
1264 fdp->fd_holdleaderscount--;
1265 if (fdp->fd_holdleaderscount == 0 &&
1266 fdp->fd_holdleaderswakeup != 0) {
1267 fdp->fd_holdleaderswakeup = 0;
1268 wakeup(&fdp->fd_holdleaderscount);
1270 FILEDESC_XUNLOCK(fdp);
1276 * Close open file descriptors.
1278 #ifndef _SYS_SYSPROTO_H_
1279 struct closefrom_args {
1285 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1287 struct filedesc *fdp;
1290 fdp = td->td_proc->p_fd;
1291 AUDIT_ARG_FD(uap->lowfd);
1294 * Treat negative starting file descriptor values identical to
1295 * closefrom(0) which closes all files.
1299 FILEDESC_SLOCK(fdp);
1300 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1301 if (fdp->fd_ofiles[fd] != NULL) {
1302 FILEDESC_SUNLOCK(fdp);
1303 (void)kern_close(td, fd);
1304 FILEDESC_SLOCK(fdp);
1307 FILEDESC_SUNLOCK(fdp);
1311 #if defined(COMPAT_43)
1313 * Return status information about a file descriptor.
1315 #ifndef _SYS_SYSPROTO_H_
1316 struct ofstat_args {
1323 ofstat(struct thread *td, struct ofstat_args *uap)
1329 error = kern_fstat(td, uap->fd, &ub);
1332 error = copyout(&oub, uap->sb, sizeof(oub));
1336 #endif /* COMPAT_43 */
1339 * Return status information about a file descriptor.
1341 #ifndef _SYS_SYSPROTO_H_
1349 sys_fstat(struct thread *td, struct fstat_args *uap)
1354 error = kern_fstat(td, uap->fd, &ub);
1356 error = copyout(&ub, uap->sb, sizeof(ub));
1361 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1368 if ((error = fget(td, fd, CAP_FSTAT, &fp)) != 0)
1371 AUDIT_ARG_FILE(td->td_proc, fp);
1373 error = fo_stat(fp, sbp, td->td_ucred, td);
1376 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1383 * Return status information about a file descriptor.
1385 #ifndef _SYS_SYSPROTO_H_
1386 struct nfstat_args {
1393 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1399 error = kern_fstat(td, uap->fd, &ub);
1401 cvtnstat(&ub, &nub);
1402 error = copyout(&nub, uap->sb, sizeof(nub));
1408 * Return pathconf information about a file descriptor.
1410 #ifndef _SYS_SYSPROTO_H_
1411 struct fpathconf_args {
1418 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1424 if ((error = fget(td, uap->fd, CAP_FPATHCONF, &fp)) != 0)
1427 /* If asynchronous I/O is available, it works for all descriptors. */
1428 if (uap->name == _PC_ASYNC_IO) {
1429 td->td_retval[0] = async_io_version;
1435 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1436 vn_lock(vp, LK_SHARED | LK_RETRY);
1437 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1439 VFS_UNLOCK_GIANT(vfslocked);
1440 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1441 if (uap->name != _PC_PIPE_BUF) {
1444 td->td_retval[0] = PIPE_BUF;
1456 * Grow the file table to accomodate (at least) nfd descriptors. This may
1457 * block and drop the filedesc lock, but it will reacquire it before
1461 fdgrowtable(struct filedesc *fdp, int nfd)
1463 struct filedesc0 *fdp0;
1464 struct freetable *fo;
1465 struct file **ntable;
1466 struct file **otable;
1468 int nnfiles, onfiles;
1471 FILEDESC_XLOCK_ASSERT(fdp);
1473 KASSERT(fdp->fd_nfiles > 0,
1474 ("zero-length file table"));
1476 /* compute the size of the new table */
1477 onfiles = fdp->fd_nfiles;
1478 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1479 if (nnfiles <= onfiles)
1480 /* the table is already large enough */
1483 /* allocate a new table and (if required) new bitmaps */
1484 FILEDESC_XUNLOCK(fdp);
1485 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1486 M_FILEDESC, M_ZERO | M_WAITOK);
1487 nfileflags = (char *)&ntable[nnfiles];
1488 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1489 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1490 M_FILEDESC, M_ZERO | M_WAITOK);
1493 FILEDESC_XLOCK(fdp);
1496 * We now have new tables ready to go. Since we dropped the
1497 * filedesc lock to call malloc(), watch out for a race.
1499 onfiles = fdp->fd_nfiles;
1500 if (onfiles >= nnfiles) {
1501 /* we lost the race, but that's OK */
1502 free(ntable, M_FILEDESC);
1504 free(nmap, M_FILEDESC);
1507 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1508 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1509 otable = fdp->fd_ofiles;
1510 fdp->fd_ofileflags = nfileflags;
1511 fdp->fd_ofiles = ntable;
1513 * We must preserve ofiles until the process exits because we can't
1514 * be certain that no threads have references to the old table via
1517 if (onfiles > NDFILE) {
1518 fo = (struct freetable *)&otable[onfiles];
1519 fdp0 = (struct filedesc0 *)fdp;
1520 fo->ft_table = otable;
1521 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1523 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1524 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1525 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1526 free(fdp->fd_map, M_FILEDESC);
1529 fdp->fd_nfiles = nnfiles;
1533 * Allocate a file descriptor for the process.
1536 fdalloc(struct thread *td, int minfd, int *result)
1538 struct proc *p = td->td_proc;
1539 struct filedesc *fdp = p->p_fd;
1545 FILEDESC_XLOCK_ASSERT(fdp);
1547 if (fdp->fd_freefile > minfd)
1548 minfd = fdp->fd_freefile;
1551 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1555 * Search the bitmap for a free descriptor. If none is found, try
1556 * to grow the file table. Keep at it until we either get a file
1557 * descriptor or run into process or system limits; fdgrowtable()
1558 * may drop the filedesc lock, so we're in a race.
1561 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1564 if (fd < fdp->fd_nfiles)
1568 error = racct_set(p, RACCT_NOFILE, min(fdp->fd_nfiles * 2, maxfd));
1573 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1577 * Perform some sanity checks, then mark the file descriptor as
1578 * used and return it to the caller.
1580 KASSERT(!fdisused(fdp, fd),
1581 ("fd_first_free() returned non-free descriptor"));
1582 KASSERT(fdp->fd_ofiles[fd] == NULL,
1583 ("free descriptor isn't"));
1584 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1591 * Allocate n file descriptors for the process.
1594 fdallocn(struct thread *td, int minfd, int *fds, int n)
1596 struct proc *p = td->td_proc;
1597 struct filedesc *fdp = p->p_fd;
1600 FILEDESC_XLOCK_ASSERT(fdp);
1602 if (!fdavail(td, n))
1605 for (i = 0; i < n; i++)
1606 if (fdalloc(td, 0, &fds[i]) != 0)
1610 for (i--; i >= 0; i--)
1611 fdunused(fdp, fds[i]);
1619 * Check to see whether n user file descriptors are available to the process
1623 fdavail(struct thread *td, int n)
1625 struct proc *p = td->td_proc;
1626 struct filedesc *fdp = td->td_proc->p_fd;
1630 FILEDESC_LOCK_ASSERT(fdp);
1633 * XXX: This is only called from uipc_usrreq.c:unp_externalize();
1634 * call racct_add() from there instead of dealing with containers
1638 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1640 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1642 last = min(fdp->fd_nfiles, lim);
1643 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1644 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1645 if (*fpp == NULL && --n <= 0)
1652 * Create a new open file structure and allocate a file decriptor for the
1653 * process that refers to it. We add one reference to the file for the
1654 * descriptor table and one reference for resultfp. This is to prevent us
1655 * being preempted and the entry in the descriptor table closed after we
1656 * release the FILEDESC lock.
1659 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1664 error = falloc_noinstall(td, &fp);
1666 return (error); /* no reference held on error */
1668 error = finstall(td, fp, &fd, flags);
1670 fdrop(fp, td); /* one reference (fp only) */
1674 if (resultfp != NULL)
1675 *resultfp = fp; /* copy out result */
1677 fdrop(fp, td); /* release local reference */
1679 if (resultfd != NULL)
1686 * Create a new open file structure without allocating a file descriptor.
1689 falloc_noinstall(struct thread *td, struct file **resultfp)
1692 int maxuserfiles = maxfiles - (maxfiles / 20);
1693 static struct timeval lastfail;
1696 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1698 if ((openfiles >= maxuserfiles &&
1699 priv_check(td, PRIV_MAXFILES) != 0) ||
1700 openfiles >= maxfiles) {
1701 if (ppsratecheck(&lastfail, &curfail, 1)) {
1702 printf("kern.maxfiles limit exceeded by uid %i, "
1703 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1707 atomic_add_int(&openfiles, 1);
1708 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1709 refcount_init(&fp->f_count, 1);
1710 fp->f_cred = crhold(td->td_ucred);
1711 fp->f_ops = &badfileops;
1719 * Install a file in a file descriptor table.
1722 finstall(struct thread *td, struct file *fp, int *fd, int flags)
1724 struct filedesc *fdp = td->td_proc->p_fd;
1727 KASSERT(fd != NULL, ("%s: fd == NULL", __func__));
1728 KASSERT(fp != NULL, ("%s: fp == NULL", __func__));
1730 FILEDESC_XLOCK(fdp);
1731 if ((error = fdalloc(td, 0, fd))) {
1732 FILEDESC_XUNLOCK(fdp);
1736 fdp->fd_ofiles[*fd] = fp;
1737 if ((flags & O_CLOEXEC) != 0)
1738 fdp->fd_ofileflags[*fd] |= UF_EXCLOSE;
1739 FILEDESC_XUNLOCK(fdp);
1744 * Build a new filedesc structure from another.
1745 * Copy the current, root, and jail root vnode references.
1748 fdinit(struct filedesc *fdp)
1750 struct filedesc0 *newfdp;
1752 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1753 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1755 FILEDESC_XLOCK(fdp);
1756 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1757 if (newfdp->fd_fd.fd_cdir)
1758 VREF(newfdp->fd_fd.fd_cdir);
1759 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1760 if (newfdp->fd_fd.fd_rdir)
1761 VREF(newfdp->fd_fd.fd_rdir);
1762 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1763 if (newfdp->fd_fd.fd_jdir)
1764 VREF(newfdp->fd_fd.fd_jdir);
1765 FILEDESC_XUNLOCK(fdp);
1768 /* Create the file descriptor table. */
1769 newfdp->fd_fd.fd_refcnt = 1;
1770 newfdp->fd_fd.fd_holdcnt = 1;
1771 newfdp->fd_fd.fd_cmask = CMASK;
1772 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1773 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1774 newfdp->fd_fd.fd_nfiles = NDFILE;
1775 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1776 newfdp->fd_fd.fd_lastfile = -1;
1777 return (&newfdp->fd_fd);
1780 static struct filedesc *
1781 fdhold(struct proc *p)
1783 struct filedesc *fdp;
1785 mtx_lock(&fdesc_mtx);
1789 mtx_unlock(&fdesc_mtx);
1794 fddrop(struct filedesc *fdp)
1796 struct filedesc0 *fdp0;
1797 struct freetable *ft;
1800 mtx_lock(&fdesc_mtx);
1801 i = --fdp->fd_holdcnt;
1802 mtx_unlock(&fdesc_mtx);
1806 FILEDESC_LOCK_DESTROY(fdp);
1807 fdp0 = (struct filedesc0 *)fdp;
1808 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1809 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1810 free(ft->ft_table, M_FILEDESC);
1812 free(fdp, M_FILEDESC);
1816 * Share a filedesc structure.
1819 fdshare(struct filedesc *fdp)
1822 FILEDESC_XLOCK(fdp);
1824 FILEDESC_XUNLOCK(fdp);
1829 * Unshare a filedesc structure, if necessary by making a copy
1832 fdunshare(struct proc *p, struct thread *td)
1835 FILEDESC_XLOCK(p->p_fd);
1836 if (p->p_fd->fd_refcnt > 1) {
1837 struct filedesc *tmp;
1839 FILEDESC_XUNLOCK(p->p_fd);
1840 tmp = fdcopy(p->p_fd);
1844 FILEDESC_XUNLOCK(p->p_fd);
1848 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1849 * this is to ease callers, not catch errors.
1852 fdcopy(struct filedesc *fdp)
1854 struct filedesc *newfdp;
1857 /* Certain daemons might not have file descriptors. */
1861 newfdp = fdinit(fdp);
1862 FILEDESC_SLOCK(fdp);
1863 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1864 FILEDESC_SUNLOCK(fdp);
1865 FILEDESC_XLOCK(newfdp);
1866 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1867 FILEDESC_XUNLOCK(newfdp);
1868 FILEDESC_SLOCK(fdp);
1870 /* copy all passable descriptors (i.e. not kqueue) */
1871 newfdp->fd_freefile = -1;
1872 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1873 if (fdisused(fdp, i) &&
1874 (fdp->fd_ofiles[i]->f_ops->fo_flags & DFLAG_PASSABLE) &&
1875 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1876 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1877 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1878 fhold(newfdp->fd_ofiles[i]);
1879 newfdp->fd_lastfile = i;
1881 if (newfdp->fd_freefile == -1)
1882 newfdp->fd_freefile = i;
1885 newfdp->fd_cmask = fdp->fd_cmask;
1886 FILEDESC_SUNLOCK(fdp);
1887 FILEDESC_XLOCK(newfdp);
1888 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1889 if (newfdp->fd_ofiles[i] != NULL)
1891 if (newfdp->fd_freefile == -1)
1892 newfdp->fd_freefile = i;
1893 FILEDESC_XUNLOCK(newfdp);
1898 * Release a filedesc structure.
1901 fdfree(struct thread *td)
1903 struct filedesc *fdp;
1906 struct filedesc_to_leader *fdtol;
1908 struct vnode *cdir, *jdir, *rdir, *vp;
1911 /* Certain daemons might not have file descriptors. */
1912 fdp = td->td_proc->p_fd;
1917 PROC_LOCK(td->td_proc);
1918 racct_set(td->td_proc, RACCT_NOFILE, 0);
1919 PROC_UNLOCK(td->td_proc);
1922 /* Check for special need to clear POSIX style locks */
1923 fdtol = td->td_proc->p_fdtol;
1924 if (fdtol != NULL) {
1925 FILEDESC_XLOCK(fdp);
1926 KASSERT(fdtol->fdl_refcount > 0,
1927 ("filedesc_to_refcount botch: fdl_refcount=%d",
1928 fdtol->fdl_refcount));
1929 if (fdtol->fdl_refcount == 1 &&
1930 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1931 for (i = 0, fpp = fdp->fd_ofiles;
1932 i <= fdp->fd_lastfile;
1935 (*fpp)->f_type != DTYPE_VNODE)
1939 FILEDESC_XUNLOCK(fdp);
1940 lf.l_whence = SEEK_SET;
1943 lf.l_type = F_UNLCK;
1945 locked = VFS_LOCK_GIANT(vp->v_mount);
1946 (void) VOP_ADVLOCK(vp,
1947 (caddr_t)td->td_proc->
1952 VFS_UNLOCK_GIANT(locked);
1953 FILEDESC_XLOCK(fdp);
1955 fpp = fdp->fd_ofiles + i;
1959 if (fdtol->fdl_refcount == 1) {
1960 if (fdp->fd_holdleaderscount > 0 &&
1961 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1963 * close() or do_dup() has cleared a reference
1964 * in a shared file descriptor table.
1966 fdp->fd_holdleaderswakeup = 1;
1967 sx_sleep(&fdp->fd_holdleaderscount,
1968 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1971 if (fdtol->fdl_holdcount > 0) {
1973 * Ensure that fdtol->fdl_leader remains
1974 * valid in closef().
1976 fdtol->fdl_wakeup = 1;
1977 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1982 fdtol->fdl_refcount--;
1983 if (fdtol->fdl_refcount == 0 &&
1984 fdtol->fdl_holdcount == 0) {
1985 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1986 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1989 td->td_proc->p_fdtol = NULL;
1990 FILEDESC_XUNLOCK(fdp);
1992 free(fdtol, M_FILEDESC_TO_LEADER);
1994 FILEDESC_XLOCK(fdp);
1995 i = --fdp->fd_refcnt;
1996 FILEDESC_XUNLOCK(fdp);
2000 fpp = fdp->fd_ofiles;
2001 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
2003 FILEDESC_XLOCK(fdp);
2006 FILEDESC_XUNLOCK(fdp);
2007 (void) closef(fp, td);
2010 FILEDESC_XLOCK(fdp);
2012 /* XXX This should happen earlier. */
2013 mtx_lock(&fdesc_mtx);
2014 td->td_proc->p_fd = NULL;
2015 mtx_unlock(&fdesc_mtx);
2017 if (fdp->fd_nfiles > NDFILE)
2018 free(fdp->fd_ofiles, M_FILEDESC);
2019 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2020 free(fdp->fd_map, M_FILEDESC);
2024 cdir = fdp->fd_cdir;
2025 fdp->fd_cdir = NULL;
2026 rdir = fdp->fd_rdir;
2027 fdp->fd_rdir = NULL;
2028 jdir = fdp->fd_jdir;
2029 fdp->fd_jdir = NULL;
2030 FILEDESC_XUNLOCK(fdp);
2033 locked = VFS_LOCK_GIANT(cdir->v_mount);
2035 VFS_UNLOCK_GIANT(locked);
2038 locked = VFS_LOCK_GIANT(rdir->v_mount);
2040 VFS_UNLOCK_GIANT(locked);
2043 locked = VFS_LOCK_GIANT(jdir->v_mount);
2045 VFS_UNLOCK_GIANT(locked);
2052 * For setugid programs, we don't want to people to use that setugidness
2053 * to generate error messages which write to a file which otherwise would
2054 * otherwise be off-limits to the process. We check for filesystems where
2055 * the vnode can change out from under us after execve (like [lin]procfs).
2057 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2058 * sufficient. We also don't check for setugidness since we know we are.
2061 is_unsafe(struct file *fp)
2063 if (fp->f_type == DTYPE_VNODE) {
2064 struct vnode *vp = fp->f_vnode;
2066 if ((vp->v_vflag & VV_PROCDEP) != 0)
2073 * Make this setguid thing safe, if at all possible.
2076 setugidsafety(struct thread *td)
2078 struct filedesc *fdp;
2081 /* Certain daemons might not have file descriptors. */
2082 fdp = td->td_proc->p_fd;
2087 * Note: fdp->fd_ofiles may be reallocated out from under us while
2088 * we are blocked in a close. Be careful!
2090 FILEDESC_XLOCK(fdp);
2091 for (i = 0; i <= fdp->fd_lastfile; i++) {
2094 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
2097 knote_fdclose(td, i);
2099 * NULL-out descriptor prior to close to avoid
2100 * a race while close blocks.
2102 fp = fdp->fd_ofiles[i];
2103 fdp->fd_ofiles[i] = NULL;
2104 fdp->fd_ofileflags[i] = 0;
2106 FILEDESC_XUNLOCK(fdp);
2107 (void) closef(fp, td);
2108 FILEDESC_XLOCK(fdp);
2111 FILEDESC_XUNLOCK(fdp);
2115 * If a specific file object occupies a specific file descriptor, close the
2116 * file descriptor entry and drop a reference on the file object. This is a
2117 * convenience function to handle a subsequent error in a function that calls
2118 * falloc() that handles the race that another thread might have closed the
2119 * file descriptor out from under the thread creating the file object.
2122 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
2125 FILEDESC_XLOCK(fdp);
2126 if (fdp->fd_ofiles[idx] == fp) {
2127 fdp->fd_ofiles[idx] = NULL;
2129 FILEDESC_XUNLOCK(fdp);
2132 FILEDESC_XUNLOCK(fdp);
2136 * Close any files on exec?
2139 fdcloseexec(struct thread *td)
2141 struct filedesc *fdp;
2144 /* Certain daemons might not have file descriptors. */
2145 fdp = td->td_proc->p_fd;
2149 FILEDESC_XLOCK(fdp);
2152 * We cannot cache fd_ofiles or fd_ofileflags since operations
2153 * may block and rip them out from under us.
2155 for (i = 0; i <= fdp->fd_lastfile; i++) {
2156 if (fdp->fd_ofiles[i] != NULL &&
2157 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2158 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2161 knote_fdclose(td, i);
2163 * NULL-out descriptor prior to close to avoid
2164 * a race while close blocks.
2166 fp = fdp->fd_ofiles[i];
2167 fdp->fd_ofiles[i] = NULL;
2168 fdp->fd_ofileflags[i] = 0;
2170 if (fp->f_type == DTYPE_MQUEUE)
2171 mq_fdclose(td, i, fp);
2172 FILEDESC_XUNLOCK(fdp);
2173 (void) closef(fp, td);
2174 FILEDESC_XLOCK(fdp);
2177 FILEDESC_XUNLOCK(fdp);
2181 * It is unsafe for set[ug]id processes to be started with file
2182 * descriptors 0..2 closed, as these descriptors are given implicit
2183 * significance in the Standard C library. fdcheckstd() will create a
2184 * descriptor referencing /dev/null for each of stdin, stdout, and
2185 * stderr that is not already open.
2188 fdcheckstd(struct thread *td)
2190 struct filedesc *fdp;
2191 register_t retval, save;
2192 int i, error, devnull;
2194 fdp = td->td_proc->p_fd;
2197 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2200 for (i = 0; i < 3; i++) {
2201 if (fdp->fd_ofiles[i] != NULL)
2204 save = td->td_retval[0];
2205 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2207 devnull = td->td_retval[0];
2208 td->td_retval[0] = save;
2211 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2213 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2222 * Internal form of close. Decrement reference count on file structure.
2223 * Note: td may be NULL when closing a file that was being passed in a
2226 * XXXRW: Giant is not required for the caller, but often will be held; this
2227 * makes it moderately likely the Giant will be recursed in the VFS case.
2230 closef(struct file *fp, struct thread *td)
2234 struct filedesc_to_leader *fdtol;
2235 struct filedesc *fdp;
2236 struct file *fp_object;
2239 * POSIX record locking dictates that any close releases ALL
2240 * locks owned by this process. This is handled by setting
2241 * a flag in the unlock to free ONLY locks obeying POSIX
2242 * semantics, and not to free BSD-style file locks.
2243 * If the descriptor was in a message, POSIX-style locks
2244 * aren't passed with the descriptor, and the thread pointer
2245 * will be NULL. Callers should be careful only to pass a
2246 * NULL thread pointer when there really is no owning
2247 * context that might have locks, or the locks will be
2250 * If this is a capability, we do lock processing under the underlying
2251 * node, not the capability itself.
2253 (void)cap_funwrap(fp, 0, &fp_object);
2254 if ((fp_object->f_type == DTYPE_VNODE) && (td != NULL)) {
2257 vp = fp_object->f_vnode;
2258 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2259 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2260 lf.l_whence = SEEK_SET;
2263 lf.l_type = F_UNLCK;
2264 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2265 F_UNLCK, &lf, F_POSIX);
2267 fdtol = td->td_proc->p_fdtol;
2268 if (fdtol != NULL) {
2270 * Handle special case where file descriptor table is
2271 * shared between multiple process leaders.
2273 fdp = td->td_proc->p_fd;
2274 FILEDESC_XLOCK(fdp);
2275 for (fdtol = fdtol->fdl_next;
2276 fdtol != td->td_proc->p_fdtol;
2277 fdtol = fdtol->fdl_next) {
2278 if ((fdtol->fdl_leader->p_flag &
2281 fdtol->fdl_holdcount++;
2282 FILEDESC_XUNLOCK(fdp);
2283 lf.l_whence = SEEK_SET;
2286 lf.l_type = F_UNLCK;
2287 vp = fp_object->f_vnode;
2288 (void) VOP_ADVLOCK(vp,
2289 (caddr_t)fdtol->fdl_leader,
2290 F_UNLCK, &lf, F_POSIX);
2291 FILEDESC_XLOCK(fdp);
2292 fdtol->fdl_holdcount--;
2293 if (fdtol->fdl_holdcount == 0 &&
2294 fdtol->fdl_wakeup != 0) {
2295 fdtol->fdl_wakeup = 0;
2299 FILEDESC_XUNLOCK(fdp);
2301 VFS_UNLOCK_GIANT(vfslocked);
2303 return (fdrop(fp, td));
2307 * Initialize the file pointer with the specified properties.
2309 * The ops are set with release semantics to be certain that the flags, type,
2310 * and data are visible when ops is. This is to prevent ops methods from being
2311 * called with bad data.
2314 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2319 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2323 fget_unlocked(struct filedesc *fdp, int fd)
2328 if (fd < 0 || fd >= fdp->fd_nfiles)
2331 * Fetch the descriptor locklessly. We avoid fdrop() races by
2332 * never raising a refcount above 0. To accomplish this we have
2333 * to use a cmpset loop rather than an atomic_add. The descriptor
2334 * must be re-verified once we acquire a reference to be certain
2335 * that the identity is still correct and we did not lose a race
2336 * due to preemption.
2339 fp = fdp->fd_ofiles[fd];
2342 count = fp->f_count;
2346 * Use an acquire barrier to prevent caching of fd_ofiles
2347 * so it is refreshed for verification.
2349 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2351 if (fp == fdp->fd_ofiles[fd])
2353 fdrop(fp, curthread);
2360 * Extract the file pointer associated with the specified descriptor for the
2361 * current user process.
2363 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2366 * If the FGET_GETCAP flag is set, the capability itself will be returned.
2367 * Calling _fget() with FGET_GETCAP on a non-capability will return EINVAL.
2368 * Otherwise, if the file is a capability, its rights will be checked against
2369 * the capability rights mask, and if successful, the object will be unwrapped.
2371 * If an error occured the non-zero error is returned and *fpp is set to
2372 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2373 * responsible for fdrop().
2375 #define FGET_GETCAP 0x00000001
2377 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2378 cap_rights_t needrights, cap_rights_t *haverightsp, u_char *maxprotp,
2381 struct filedesc *fdp;
2384 struct file *fp_fromcap;
2389 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2391 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2393 if (fp->f_ops == &badfileops) {
2400 * If this is a capability, what rights does it have?
2402 if (haverightsp != NULL) {
2403 if (fp->f_type == DTYPE_CAPABILITY)
2404 *haverightsp = cap_rights(fp);
2406 *haverightsp = CAP_MASK_VALID;
2410 * If a capability has been requested, return the capability directly.
2411 * Otherwise, check capability rights, extract the underlying object,
2412 * and check its access flags.
2414 if (fget_flags & FGET_GETCAP) {
2415 if (fp->f_type != DTYPE_CAPABILITY) {
2420 if (maxprotp == NULL)
2421 error = cap_funwrap(fp, needrights, &fp_fromcap);
2423 error = cap_funwrap_mmap(fp, needrights, maxprotp,
2431 * If we've unwrapped a file, drop the original capability
2432 * and hold the new descriptor. fp after this point refers to
2433 * the actual (unwrapped) object, not the capability.
2435 if (fp != fp_fromcap) {
2441 #else /* !CAPABILITIES */
2442 KASSERT(fp->f_type != DTYPE_CAPABILITY,
2443 ("%s: saw capability", __func__));
2444 if (maxprotp != NULL)
2445 *maxprotp = VM_PROT_ALL;
2446 #endif /* CAPABILITIES */
2449 * FREAD and FWRITE failure return EBADF as per POSIX.
2455 if ((fp->f_flag & flags) == 0)
2459 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2460 ((fp->f_flag & FWRITE) != 0))
2466 KASSERT(0, ("wrong flags"));
2479 fget(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2482 return(_fget(td, fd, fpp, 0, rights, NULL, NULL, 0));
2486 fget_mmap(struct thread *td, int fd, cap_rights_t rights, u_char *maxprotp,
2490 return (_fget(td, fd, fpp, 0, rights, NULL, maxprotp, 0));
2494 fget_read(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2497 return(_fget(td, fd, fpp, FREAD, rights, NULL, NULL, 0));
2501 fget_write(struct thread *td, int fd, cap_rights_t rights, struct file **fpp)
2504 return (_fget(td, fd, fpp, FWRITE, rights, NULL, NULL, 0));
2508 * Unlike the other fget() calls, which accept and check capability rights
2509 * but never return capabilities, fgetcap() returns the capability but doesn't
2510 * check capability rights.
2513 fgetcap(struct thread *td, int fd, struct file **fpp)
2516 return (_fget(td, fd, fpp, 0, 0, NULL, NULL, FGET_GETCAP));
2521 * Like fget() but loads the underlying vnode, or returns an error if the
2522 * descriptor does not represent a vnode. Note that pipes use vnodes but
2523 * never have VM objects. The returned vnode will be vref()'d.
2525 * XXX: what about the unused flags ?
2528 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t needrights,
2529 cap_rights_t *haverightsp, struct vnode **vpp)
2535 if ((error = _fget(td, fd, &fp, flags, needrights, haverightsp,
2538 if (fp->f_vnode == NULL) {
2550 fgetvp(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2553 return (_fgetvp(td, fd, 0, rights, NULL, vpp));
2557 fgetvp_rights(struct thread *td, int fd, cap_rights_t need, cap_rights_t *have,
2560 return (_fgetvp(td, fd, 0, need, have, vpp));
2564 fgetvp_read(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2567 return (_fgetvp(td, fd, FREAD, rights, NULL, vpp));
2571 fgetvp_exec(struct thread *td, int fd, cap_rights_t rights, struct vnode **vpp)
2574 return (_fgetvp(td, fd, FEXEC, rights, NULL, vpp));
2579 fgetvp_write(struct thread *td, int fd, cap_rights_t rights,
2583 return (_fgetvp(td, fd, FWRITE, rights, NULL, vpp));
2588 * Like fget() but loads the underlying socket, or returns an error if the
2589 * descriptor does not represent a socket.
2591 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2594 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2595 * on their file descriptor reference to prevent the socket from being free'd
2599 fgetsock(struct thread *td, int fd, cap_rights_t rights, struct socket **spp,
2608 if ((error = _fget(td, fd, &fp, 0, rights, NULL, NULL, 0)) != 0)
2610 if (fp->f_type != DTYPE_SOCKET) {
2615 *fflagp = fp->f_flag;
2626 * Drop the reference count on the socket and XXX release the SX lock in the
2627 * future. The last reference closes the socket.
2629 * Note: fputsock() is deprecated, see comment for fgetsock().
2632 fputsock(struct socket *so)
2637 CURVNET_SET(so->so_vnet);
2643 * Handle the last reference to a file being closed.
2645 * No special capability handling here, as the capability's fo_close will run
2646 * instead of the object here, and perform any necessary drop on the object.
2649 _fdrop(struct file *fp, struct thread *td)
2654 if (fp->f_count != 0)
2655 panic("fdrop: count %d", fp->f_count);
2656 if (fp->f_ops != &badfileops)
2657 error = fo_close(fp, td);
2658 atomic_subtract_int(&openfiles, 1);
2660 free(fp->f_advice, M_FADVISE);
2661 uma_zfree(file_zone, fp);
2667 * Apply an advisory lock on a file descriptor.
2669 * Just attempt to get a record lock of the requested type on the entire file
2670 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2672 #ifndef _SYS_SYSPROTO_H_
2680 sys_flock(struct thread *td, struct flock_args *uap)
2688 if ((error = fget(td, uap->fd, CAP_FLOCK, &fp)) != 0)
2690 if (fp->f_type != DTYPE_VNODE) {
2692 return (EOPNOTSUPP);
2696 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2697 lf.l_whence = SEEK_SET;
2700 if (uap->how & LOCK_UN) {
2701 lf.l_type = F_UNLCK;
2702 atomic_clear_int(&fp->f_flag, FHASLOCK);
2703 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2706 if (uap->how & LOCK_EX)
2707 lf.l_type = F_WRLCK;
2708 else if (uap->how & LOCK_SH)
2709 lf.l_type = F_RDLCK;
2714 atomic_set_int(&fp->f_flag, FHASLOCK);
2715 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2716 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2719 VFS_UNLOCK_GIANT(vfslocked);
2723 * Duplicate the specified descriptor to a free descriptor.
2726 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2732 * If the to-be-dup'd fd number is greater than the allowed number
2733 * of file descriptors, or the fd to be dup'd has already been
2734 * closed, then reject.
2736 FILEDESC_XLOCK(fdp);
2737 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2738 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2739 FILEDESC_XUNLOCK(fdp);
2744 * There are two cases of interest here.
2746 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2748 * For ENXIO steal away the file structure from (dfd) and store it in
2749 * (indx). (dfd) is effectively closed by this operation.
2751 * Any other error code is just returned.
2756 * Check that the mode the file is being opened for is a
2757 * subset of the mode of the existing descriptor.
2759 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2760 FILEDESC_XUNLOCK(fdp);
2763 fp = fdp->fd_ofiles[indx];
2764 fdp->fd_ofiles[indx] = wfp;
2765 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2769 FILEDESC_XUNLOCK(fdp);
2772 * We now own the reference to fp that the ofiles[]
2773 * array used to own. Release it.
2780 * Steal away the file pointer from dfd and stuff it into indx.
2782 fp = fdp->fd_ofiles[indx];
2783 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2784 fdp->fd_ofiles[dfd] = NULL;
2785 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2786 fdp->fd_ofileflags[dfd] = 0;
2790 FILEDESC_XUNLOCK(fdp);
2793 * We now own the reference to fp that the ofiles[] array
2794 * used to own. Release it.
2801 FILEDESC_XUNLOCK(fdp);
2808 * Scan all active processes and prisons to see if any of them have a current
2809 * or root directory of `olddp'. If so, replace them with the new mount point.
2812 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2814 struct filedesc *fdp;
2819 if (vrefcnt(olddp) == 1)
2822 sx_slock(&allproc_lock);
2823 FOREACH_PROC_IN_SYSTEM(p) {
2827 FILEDESC_XLOCK(fdp);
2828 if (fdp->fd_cdir == olddp) {
2830 fdp->fd_cdir = newdp;
2833 if (fdp->fd_rdir == olddp) {
2835 fdp->fd_rdir = newdp;
2838 if (fdp->fd_jdir == olddp) {
2840 fdp->fd_jdir = newdp;
2843 FILEDESC_XUNLOCK(fdp);
2846 sx_sunlock(&allproc_lock);
2847 if (rootvnode == olddp) {
2852 mtx_lock(&prison0.pr_mtx);
2853 if (prison0.pr_root == olddp) {
2855 prison0.pr_root = newdp;
2858 mtx_unlock(&prison0.pr_mtx);
2859 sx_slock(&allprison_lock);
2860 TAILQ_FOREACH(pr, &allprison, pr_list) {
2861 mtx_lock(&pr->pr_mtx);
2862 if (pr->pr_root == olddp) {
2864 pr->pr_root = newdp;
2867 mtx_unlock(&pr->pr_mtx);
2869 sx_sunlock(&allprison_lock);
2874 struct filedesc_to_leader *
2875 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2877 struct filedesc_to_leader *fdtol;
2879 fdtol = malloc(sizeof(struct filedesc_to_leader),
2880 M_FILEDESC_TO_LEADER,
2882 fdtol->fdl_refcount = 1;
2883 fdtol->fdl_holdcount = 0;
2884 fdtol->fdl_wakeup = 0;
2885 fdtol->fdl_leader = leader;
2887 FILEDESC_XLOCK(fdp);
2888 fdtol->fdl_next = old->fdl_next;
2889 fdtol->fdl_prev = old;
2890 old->fdl_next = fdtol;
2891 fdtol->fdl_next->fdl_prev = fdtol;
2892 FILEDESC_XUNLOCK(fdp);
2894 fdtol->fdl_next = fdtol;
2895 fdtol->fdl_prev = fdtol;
2901 * Get file structures globally.
2904 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2907 struct filedesc *fdp;
2912 error = sysctl_wire_old_buffer(req, 0);
2915 if (req->oldptr == NULL) {
2917 sx_slock(&allproc_lock);
2918 FOREACH_PROC_IN_SYSTEM(p) {
2919 if (p->p_state == PRS_NEW)
2924 /* overestimates sparse tables. */
2925 if (fdp->fd_lastfile > 0)
2926 n += fdp->fd_lastfile;
2929 sx_sunlock(&allproc_lock);
2930 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2933 bzero(&xf, sizeof(xf));
2934 xf.xf_size = sizeof(xf);
2935 sx_slock(&allproc_lock);
2936 FOREACH_PROC_IN_SYSTEM(p) {
2938 if (p->p_state == PRS_NEW) {
2942 if (p_cansee(req->td, p) != 0) {
2946 xf.xf_pid = p->p_pid;
2947 xf.xf_uid = p->p_ucred->cr_uid;
2952 FILEDESC_SLOCK(fdp);
2953 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2954 if ((fp = fdp->fd_ofiles[n]) == NULL)
2958 xf.xf_data = fp->f_data;
2959 xf.xf_vnode = fp->f_vnode;
2960 xf.xf_type = fp->f_type;
2961 xf.xf_count = fp->f_count;
2963 xf.xf_offset = foffset_get(fp);
2964 xf.xf_flag = fp->f_flag;
2965 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2969 FILEDESC_SUNLOCK(fdp);
2974 sx_sunlock(&allproc_lock);
2978 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2979 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2981 #ifdef KINFO_OFILE_SIZE
2982 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2985 #ifdef COMPAT_FREEBSD7
2987 export_vnode_for_osysctl(struct vnode *vp, int type,
2988 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2991 char *fullpath, *freepath;
2994 bzero(kif, sizeof(*kif));
2995 kif->kf_structsize = sizeof(*kif);
2999 kif->kf_type = KF_TYPE_VNODE;
3000 /* This function only handles directories. */
3001 if (vp->v_type != VDIR) {
3005 kif->kf_vnode_type = KF_VTYPE_VDIR;
3008 * This is not a true file descriptor, so we set a bogus refcount
3009 * and offset to indicate these fields should be ignored.
3011 kif->kf_ref_count = -1;
3012 kif->kf_offset = -1;
3016 FILEDESC_SUNLOCK(fdp);
3017 vn_fullpath(curthread, vp, &fullpath, &freepath);
3018 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3020 VFS_UNLOCK_GIANT(vfslocked);
3021 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3022 if (freepath != NULL)
3023 free(freepath, M_TEMP);
3024 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3025 FILEDESC_SLOCK(fdp);
3030 * Get per-process file descriptors for use by procstat(1), et al.
3033 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3035 char *fullpath, *freepath;
3036 struct kinfo_ofile *kif;
3037 struct filedesc *fdp;
3038 int error, i, *name;
3039 struct shmfd *shmfd;
3049 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3056 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3057 FILEDESC_SLOCK(fdp);
3058 if (fdp->fd_cdir != NULL)
3059 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3061 if (fdp->fd_rdir != NULL)
3062 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3064 if (fdp->fd_jdir != NULL)
3065 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3067 for (i = 0; i < fdp->fd_nfiles; i++) {
3068 if ((fp = fdp->fd_ofiles[i]) == NULL)
3070 bzero(kif, sizeof(*kif));
3071 kif->kf_structsize = sizeof(*kif);
3081 * When reporting a capability, most fields will be from the
3082 * underlying object, but do mark as a capability. With
3083 * ofiledesc, we don't have a field to export the cap_rights_t,
3084 * but we do with the new filedesc.
3086 if (fp->f_type == DTYPE_CAPABILITY) {
3087 kif->kf_flags |= KF_FLAG_CAPABILITY;
3088 (void)cap_funwrap(fp, 0, &fp);
3091 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3092 ("sysctl_kern_proc_ofiledesc: saw capability"));
3094 switch (fp->f_type) {
3096 kif->kf_type = KF_TYPE_VNODE;
3101 kif->kf_type = KF_TYPE_SOCKET;
3106 kif->kf_type = KF_TYPE_PIPE;
3110 kif->kf_type = KF_TYPE_FIFO;
3115 kif->kf_type = KF_TYPE_KQUEUE;
3119 kif->kf_type = KF_TYPE_CRYPTO;
3123 kif->kf_type = KF_TYPE_MQUEUE;
3127 kif->kf_type = KF_TYPE_SHM;
3132 kif->kf_type = KF_TYPE_SEM;
3137 kif->kf_type = KF_TYPE_PTS;
3142 case DTYPE_PROCDESC:
3143 kif->kf_type = KF_TYPE_PROCDESC;
3148 kif->kf_type = KF_TYPE_UNKNOWN;
3151 kif->kf_ref_count = fp->f_count;
3152 if (fp->f_flag & FREAD)
3153 kif->kf_flags |= KF_FLAG_READ;
3154 if (fp->f_flag & FWRITE)
3155 kif->kf_flags |= KF_FLAG_WRITE;
3156 if (fp->f_flag & FAPPEND)
3157 kif->kf_flags |= KF_FLAG_APPEND;
3158 if (fp->f_flag & FASYNC)
3159 kif->kf_flags |= KF_FLAG_ASYNC;
3160 if (fp->f_flag & FFSYNC)
3161 kif->kf_flags |= KF_FLAG_FSYNC;
3162 if (fp->f_flag & FNONBLOCK)
3163 kif->kf_flags |= KF_FLAG_NONBLOCK;
3164 if (fp->f_flag & O_DIRECT)
3165 kif->kf_flags |= KF_FLAG_DIRECT;
3166 if (fp->f_flag & FHASLOCK)
3167 kif->kf_flags |= KF_FLAG_HASLOCK;
3168 kif->kf_offset = foffset_get(fp);
3171 switch (vp->v_type) {
3173 kif->kf_vnode_type = KF_VTYPE_VNON;
3176 kif->kf_vnode_type = KF_VTYPE_VREG;
3179 kif->kf_vnode_type = KF_VTYPE_VDIR;
3182 kif->kf_vnode_type = KF_VTYPE_VBLK;
3185 kif->kf_vnode_type = KF_VTYPE_VCHR;
3188 kif->kf_vnode_type = KF_VTYPE_VLNK;
3191 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3194 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3197 kif->kf_vnode_type = KF_VTYPE_VBAD;
3200 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3204 * It is OK to drop the filedesc lock here as we will
3205 * re-validate and re-evaluate its properties when
3206 * the loop continues.
3210 FILEDESC_SUNLOCK(fdp);
3211 vn_fullpath(curthread, vp, &fullpath, &freepath);
3212 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3214 VFS_UNLOCK_GIANT(vfslocked);
3215 strlcpy(kif->kf_path, fullpath,
3216 sizeof(kif->kf_path));
3217 if (freepath != NULL)
3218 free(freepath, M_TEMP);
3219 FILEDESC_SLOCK(fdp);
3222 struct sockaddr *sa;
3224 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3225 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3226 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3229 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3230 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3231 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3234 kif->kf_sock_domain =
3235 so->so_proto->pr_domain->dom_family;
3236 kif->kf_sock_type = so->so_type;
3237 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3240 strlcpy(kif->kf_path, tty_devname(tp),
3241 sizeof(kif->kf_path));
3244 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3245 if (ks != NULL && ksem_info != NULL)
3246 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3247 error = SYSCTL_OUT(req, kif, sizeof(*kif));
3251 FILEDESC_SUNLOCK(fdp);
3257 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
3258 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
3259 #endif /* COMPAT_FREEBSD7 */
3261 #ifdef KINFO_FILE_SIZE
3262 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3265 struct export_fd_buf {
3266 struct filedesc *fdp;
3269 struct kinfo_file kif;
3273 export_fd_to_sb(void *data, int type, int fd, int fflags, int refcnt,
3274 int64_t offset, int fd_is_cap, cap_rights_t fd_cap_rights,
3275 struct export_fd_buf *efbuf)
3280 } fflags_table[] = {
3281 { FAPPEND, KF_FLAG_APPEND },
3282 { FASYNC, KF_FLAG_ASYNC },
3283 { FFSYNC, KF_FLAG_FSYNC },
3284 { FHASLOCK, KF_FLAG_HASLOCK },
3285 { FNONBLOCK, KF_FLAG_NONBLOCK },
3286 { FREAD, KF_FLAG_READ },
3287 { FWRITE, KF_FLAG_WRITE },
3288 { O_CREAT, KF_FLAG_CREAT },
3289 { O_DIRECT, KF_FLAG_DIRECT },
3290 { O_EXCL, KF_FLAG_EXCL },
3291 { O_EXEC, KF_FLAG_EXEC },
3292 { O_EXLOCK, KF_FLAG_EXLOCK },
3293 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3294 { O_SHLOCK, KF_FLAG_SHLOCK },
3295 { O_TRUNC, KF_FLAG_TRUNC }
3297 #define NFFLAGS (sizeof(fflags_table) / sizeof(*fflags_table))
3298 struct kinfo_file *kif;
3300 int error, locked, vfslocked;
3303 if (efbuf->remainder == 0)
3306 bzero(kif, sizeof(*kif));
3307 locked = efbuf->fdp != NULL;
3312 FILEDESC_SUNLOCK(efbuf->fdp);
3315 vp = (struct vnode *)data;
3316 error = fill_vnode_info(vp, kif);
3317 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3319 VFS_UNLOCK_GIANT(vfslocked);
3321 case KF_TYPE_SOCKET:
3322 error = fill_socket_info((struct socket *)data, kif);
3325 error = fill_pipe_info((struct pipe *)data, kif);
3328 error = fill_pts_info((struct tty *)data, kif);
3330 case KF_TYPE_PROCDESC:
3331 error = fill_procdesc_info((struct procdesc *)data, kif);
3334 error = fill_sem_info((struct file *)data, kif);
3337 error = fill_shm_info((struct file *)data, kif);
3343 kif->kf_status |= KF_ATTR_VALID;
3346 * Translate file access flags.
3348 for (i = 0; i < NFFLAGS; i++)
3349 if (fflags & fflags_table[i].fflag)
3350 kif->kf_flags |= fflags_table[i].kf_fflag;
3352 kif->kf_flags |= KF_FLAG_CAPABILITY;
3354 kif->kf_cap_rights = fd_cap_rights;
3356 kif->kf_type = type;
3357 kif->kf_ref_count = refcnt;
3358 kif->kf_offset = offset;
3359 /* Pack record size down */
3360 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3361 strlen(kif->kf_path) + 1;
3362 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3363 if (efbuf->remainder != -1) {
3364 if (efbuf->remainder < kif->kf_structsize) {
3365 /* Terminate export. */
3366 efbuf->remainder = 0;
3367 if (efbuf->fdp != NULL && !locked)
3368 FILEDESC_SLOCK(efbuf->fdp);
3371 efbuf->remainder -= kif->kf_structsize;
3374 FILEDESC_SUNLOCK(efbuf->fdp);
3375 error = sbuf_bcat(efbuf->sb, kif, kif->kf_structsize);
3376 if (efbuf->fdp != NULL)
3377 FILEDESC_SLOCK(efbuf->fdp);
3382 * Store a process file descriptor information to sbuf.
3384 * Takes a locked proc as argument, and returns with the proc unlocked.
3387 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3390 struct filedesc *fdp;
3391 struct export_fd_buf *efbuf;
3392 struct vnode *cttyvp, *textvp, *tracevp;
3396 int fd_is_cap, type, refcnt, fflags;
3397 cap_rights_t fd_cap_rights;
3399 PROC_LOCK_ASSERT(p, MA_OWNED);
3402 tracevp = p->p_tracevp;
3403 if (tracevp != NULL)
3406 textvp = p->p_textvp;
3409 /* Controlling tty. */
3411 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3412 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3418 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3421 efbuf->remainder = maxlen;
3422 if (tracevp != NULL)
3423 export_fd_to_sb(tracevp, KF_TYPE_VNODE, KF_FD_TYPE_TRACE,
3424 FREAD | FWRITE, -1, -1, 0, 0, efbuf);
3426 export_fd_to_sb(textvp, KF_TYPE_VNODE, KF_FD_TYPE_TEXT,
3427 FREAD, -1, -1, 0, 0, efbuf);
3429 export_fd_to_sb(cttyvp, KF_TYPE_VNODE, KF_FD_TYPE_CTTY,
3430 FREAD | FWRITE, -1, -1, 0, 0, efbuf);
3435 FILEDESC_SLOCK(fdp);
3436 /* working directory */
3437 if (fdp->fd_cdir != NULL) {
3439 data = fdp->fd_cdir;
3440 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_CWD,
3441 FREAD, -1, -1, 0, 0, efbuf);
3443 /* root directory */
3444 if (fdp->fd_rdir != NULL) {
3446 data = fdp->fd_rdir;
3447 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_ROOT,
3448 FREAD, -1, -1, 0, 0, efbuf);
3450 /* jail directory */
3451 if (fdp->fd_jdir != NULL) {
3453 data = fdp->fd_jdir;
3454 export_fd_to_sb(data, KF_TYPE_VNODE, KF_FD_TYPE_JAIL,
3455 FREAD, -1, -1, 0, 0, efbuf);
3457 for (i = 0; i < fdp->fd_nfiles; i++) {
3458 if ((fp = fdp->fd_ofiles[i]) == NULL)
3466 * When reporting a capability, most fields will be from the
3467 * underlying object, but do mark as a capability and export
3468 * the capability rights mask.
3470 if (fp->f_type == DTYPE_CAPABILITY) {
3472 fd_cap_rights = cap_rights(fp);
3473 (void)cap_funwrap(fp, 0, &fp);
3475 #else /* !CAPABILITIES */
3476 KASSERT(fp->f_type != DTYPE_CAPABILITY,
3477 ("sysctl_kern_proc_filedesc: saw capability"));
3479 switch (fp->f_type) {
3481 type = KF_TYPE_VNODE;
3487 type = KF_TYPE_SOCKET;
3492 type = KF_TYPE_PIPE;
3497 type = KF_TYPE_FIFO;
3503 type = KF_TYPE_KQUEUE;
3507 type = KF_TYPE_CRYPTO;
3511 type = KF_TYPE_MQUEUE;
3530 case DTYPE_PROCDESC:
3531 type = KF_TYPE_PROCDESC;
3537 type = KF_TYPE_UNKNOWN;
3540 refcnt = fp->f_count;
3541 fflags = fp->f_flag;
3542 offset = foffset_get(fp);
3545 * Create sysctl entry.
3546 * It is OK to drop the filedesc lock here as we will
3547 * re-validate and re-evaluate its properties when
3548 * the loop continues.
3550 error = export_fd_to_sb(data, type, i, fflags, refcnt,
3551 offset, fd_is_cap, fd_cap_rights, efbuf);
3555 FILEDESC_SUNLOCK(fdp);
3558 free(efbuf, M_TEMP);
3562 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3565 * Get per-process file descriptors for use by procstat(1), et al.
3568 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3573 int error, error2, *name;
3577 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3578 error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
3583 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3584 error = kern_proc_filedesc_out(p, &sb, maxlen);
3585 error2 = sbuf_finish(&sb);
3587 return (error != 0 ? error : error2);
3591 vntype_to_kinfo(int vtype)
3596 } vtypes_table[] = {
3597 { VBAD, KF_VTYPE_VBAD },
3598 { VBLK, KF_VTYPE_VBLK },
3599 { VCHR, KF_VTYPE_VCHR },
3600 { VDIR, KF_VTYPE_VDIR },
3601 { VFIFO, KF_VTYPE_VFIFO },
3602 { VLNK, KF_VTYPE_VLNK },
3603 { VNON, KF_VTYPE_VNON },
3604 { VREG, KF_VTYPE_VREG },
3605 { VSOCK, KF_VTYPE_VSOCK }
3607 #define NVTYPES (sizeof(vtypes_table) / sizeof(*vtypes_table))
3611 * Perform vtype translation.
3613 for (i = 0; i < NVTYPES; i++)
3614 if (vtypes_table[i].vtype == vtype)
3617 return (vtypes_table[i].kf_vtype);
3619 return (KF_VTYPE_UNKNOWN);
3623 fill_vnode_info(struct vnode *vp, struct kinfo_file *kif)
3626 char *fullpath, *freepath;
3627 int error, vfslocked;
3631 kif->kf_vnode_type = vntype_to_kinfo(vp->v_type);
3634 error = vn_fullpath(curthread, vp, &fullpath, &freepath);
3636 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3638 if (freepath != NULL)
3639 free(freepath, M_TEMP);
3642 * Retrieve vnode attributes.
3644 va.va_fsid = VNOVAL;
3646 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3647 vn_lock(vp, LK_SHARED | LK_RETRY);
3648 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3650 VFS_UNLOCK_GIANT(vfslocked);
3653 if (va.va_fsid != VNOVAL)
3654 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3656 kif->kf_un.kf_file.kf_file_fsid =
3657 vp->v_mount->mnt_stat.f_fsid.val[0];
3658 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3659 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3660 kif->kf_un.kf_file.kf_file_size = va.va_size;
3661 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3666 fill_socket_info(struct socket *so, struct kinfo_file *kif)
3668 struct sockaddr *sa;
3669 struct inpcb *inpcb;
3670 struct unpcb *unpcb;
3675 kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
3676 kif->kf_sock_type = so->so_type;
3677 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3678 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
3679 switch(kif->kf_sock_domain) {
3682 if (kif->kf_sock_protocol == IPPROTO_TCP) {
3683 if (so->so_pcb != NULL) {
3684 inpcb = (struct inpcb *)(so->so_pcb);
3685 kif->kf_un.kf_sock.kf_sock_inpcb =
3686 (uintptr_t)inpcb->inp_ppcb;
3691 if (so->so_pcb != NULL) {
3692 unpcb = (struct unpcb *)(so->so_pcb);
3693 if (unpcb->unp_conn) {
3694 kif->kf_un.kf_sock.kf_sock_unpconn =
3695 (uintptr_t)unpcb->unp_conn;
3696 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
3697 so->so_rcv.sb_state;
3698 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
3699 so->so_snd.sb_state;
3704 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
3705 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3706 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3709 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
3710 if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3711 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3714 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
3715 sizeof(kif->kf_path));
3720 fill_pts_info(struct tty *tp, struct kinfo_file *kif)
3725 kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
3726 strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
3731 fill_pipe_info(struct pipe *pi, struct kinfo_file *kif)
3736 kif->kf_un.kf_pipe.kf_pipe_addr = (uintptr_t)pi;
3737 kif->kf_un.kf_pipe.kf_pipe_peer = (uintptr_t)pi->pipe_peer;
3738 kif->kf_un.kf_pipe.kf_pipe_buffer_cnt = pi->pipe_buffer.cnt;
3743 fill_procdesc_info(struct procdesc *pdp, struct kinfo_file *kif)
3748 kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
3753 fill_sem_info(struct file *fp, struct kinfo_file *kif)
3759 if (fp->f_data == NULL)
3761 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3763 if (ksem_info == NULL)
3765 ksem_info(fp->f_data, kif->kf_path, sizeof(kif->kf_path),
3766 &kif->kf_un.kf_sem.kf_sem_value);
3767 kif->kf_un.kf_sem.kf_sem_mode = sb.st_mode;
3772 fill_shm_info(struct file *fp, struct kinfo_file *kif)
3778 if (fp->f_data == NULL)
3780 if (fo_stat(fp, &sb, td->td_ucred, td) != 0)
3782 shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
3783 kif->kf_un.kf_file.kf_file_mode = sb.st_mode;
3784 kif->kf_un.kf_file.kf_file_size = sb.st_size;
3788 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3789 sysctl_kern_proc_filedesc, "Process filedesc entries");
3793 * For the purposes of debugging, generate a human-readable string for the
3797 file_type_to_name(short type)
3827 * For the purposes of debugging, identify a process (if any, perhaps one of
3828 * many) that references the passed file in its file descriptor array. Return
3831 static struct proc *
3832 file_to_first_proc(struct file *fp)
3834 struct filedesc *fdp;
3838 FOREACH_PROC_IN_SYSTEM(p) {
3839 if (p->p_state == PRS_NEW)
3844 for (n = 0; n < fdp->fd_nfiles; n++) {
3845 if (fp == fdp->fd_ofiles[n])
3853 db_print_file(struct file *fp, int header)
3858 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3859 "File", "Type", "Data", "Flag", "GCFl", "Count",
3860 "MCount", "Vnode", "FPID", "FCmd");
3861 p = file_to_first_proc(fp);
3862 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3863 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3864 0, fp->f_count, 0, fp->f_vnode,
3865 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3868 DB_SHOW_COMMAND(file, db_show_file)
3873 db_printf("usage: show file <addr>\n");
3876 fp = (struct file *)addr;
3877 db_print_file(fp, 1);
3880 DB_SHOW_COMMAND(files, db_show_files)
3882 struct filedesc *fdp;
3889 FOREACH_PROC_IN_SYSTEM(p) {
3890 if (p->p_state == PRS_NEW)
3892 if ((fdp = p->p_fd) == NULL)
3894 for (n = 0; n < fdp->fd_nfiles; ++n) {
3895 if ((fp = fdp->fd_ofiles[n]) == NULL)
3897 db_print_file(fp, header);
3904 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3905 &maxfilesperproc, 0, "Maximum files allowed open per process");
3907 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3908 &maxfiles, 0, "Maximum number of files");
3910 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3911 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3915 filelistinit(void *dummy)
3918 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3919 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3920 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3921 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3923 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3925 /*-------------------------------------------------------------------*/
3928 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3929 int flags, struct thread *td)
3936 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3944 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3952 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3960 badfo_kqfilter(struct file *fp, struct knote *kn)
3967 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3975 badfo_close(struct file *fp, struct thread *td)
3982 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3990 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3997 struct fileops badfileops = {
3998 .fo_read = badfo_readwrite,
3999 .fo_write = badfo_readwrite,
4000 .fo_truncate = badfo_truncate,
4001 .fo_ioctl = badfo_ioctl,
4002 .fo_poll = badfo_poll,
4003 .fo_kqfilter = badfo_kqfilter,
4004 .fo_stat = badfo_stat,
4005 .fo_close = badfo_close,
4006 .fo_chmod = badfo_chmod,
4007 .fo_chown = badfo_chown,
4011 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
4019 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
4026 /*-------------------------------------------------------------------*/
4029 * File Descriptor pseudo-device driver (/dev/fd/).
4031 * Opening minor device N dup()s the file (if any) connected to file
4032 * descriptor N belonging to the calling process. Note that this driver
4033 * consists of only the ``open()'' routine, because all subsequent
4034 * references to this file will be direct to the other driver.
4036 * XXX: we could give this one a cloning event handler if necessary.
4041 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
4045 * XXX Kludge: set curthread->td_dupfd to contain the value of the
4046 * the file descriptor being sought for duplication. The error
4047 * return ensures that the vnode for this device will be released
4048 * by vn_open. Open will detect this special error and take the
4049 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
4050 * will simply report the error.
4052 td->td_dupfd = dev2unit(dev);
4056 static struct cdevsw fildesc_cdevsw = {
4057 .d_version = D_VERSION,
4063 fildesc_drvinit(void *unused)
4067 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
4068 UID_ROOT, GID_WHEEL, 0666, "fd/0");
4069 make_dev_alias(dev, "stdin");
4070 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
4071 UID_ROOT, GID_WHEEL, 0666, "fd/1");
4072 make_dev_alias(dev, "stdout");
4073 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
4074 UID_ROOT, GID_WHEEL, 0666, "fd/2");
4075 make_dev_alias(dev, "stderr");
4078 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);