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_compat.h"
42 #include "opt_ktrace.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
48 #include <sys/domain.h>
49 #include <sys/fcntl.h>
51 #include <sys/filedesc.h>
52 #include <sys/filio.h>
54 #include <sys/kernel.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mqueue.h>
62 #include <sys/mutex.h>
63 #include <sys/namei.h>
66 #include <sys/protosw.h>
67 #include <sys/resourcevar.h>
68 #include <sys/signalvar.h>
69 #include <sys/socketvar.h>
72 #include <sys/syscallsubr.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
76 #include <sys/unistd.h>
78 #include <sys/vnode.h>
80 #include <sys/ktrace.h>
85 #include <security/audit/audit.h>
91 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
92 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
93 "file desc to leader structures");
94 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
96 MALLOC_DECLARE(M_FADVISE);
98 static uma_zone_t file_zone;
100 void (*ksem_info)(struct ksem *ks, char *path, size_t size, uint32_t *value);
102 /* Flags for do_dup() */
103 #define DUP_FIXED 0x1 /* Force fixed allocation */
104 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
105 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
107 static int do_dup(struct thread *td, int flags, int old, int new,
109 static int fd_first_free(struct filedesc *, int, int);
110 static int fd_last_used(struct filedesc *, int, int);
111 static void fdgrowtable(struct filedesc *, int);
112 static void fdunused(struct filedesc *fdp, int fd);
113 static void fdused(struct filedesc *fdp, int fd);
116 * A process is initially started out with NDFILE descriptors stored within
117 * this structure, selected to be enough for typical applications based on
118 * the historical limit of 20 open files (and the usage of descriptors by
119 * shells). If these descriptors are exhausted, a larger descriptor table
120 * may be allocated, up to a process' resource limit; the internal arrays
124 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
125 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
126 #define NDSLOT(x) ((x) / NDENTRIES)
127 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
128 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
131 * Storage required per open file descriptor.
133 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
136 * Storage to hold unused ofiles that need to be reclaimed.
139 struct file **ft_table;
140 SLIST_ENTRY(freetable) ft_next;
144 * Basic allocation of descriptors:
145 * one of the above, plus arrays for NDFILE descriptors.
148 struct filedesc fd_fd;
150 * ofiles which need to be reclaimed on free.
152 SLIST_HEAD(,freetable) fd_free;
154 * These arrays are used when the number of open files is
155 * <= NDFILE, and are then pointed to by the pointers above.
157 struct file *fd_dfiles[NDFILE];
158 char fd_dfileflags[NDFILE];
159 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
163 * Descriptor management.
165 volatile int openfiles; /* actual number of open files */
166 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
167 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
169 /* A mutex to protect the association between a proc and filedesc. */
170 static struct mtx fdesc_mtx;
173 * Find the first zero bit in the given bitmap, starting at low and not
174 * exceeding size - 1.
177 fd_first_free(struct filedesc *fdp, int low, int size)
179 NDSLOTTYPE *map = fdp->fd_map;
187 if (low % NDENTRIES) {
188 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
189 if ((mask &= ~map[off]) != 0UL)
190 return (off * NDENTRIES + ffsl(mask) - 1);
193 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
194 if (map[off] != ~0UL)
195 return (off * NDENTRIES + ffsl(~map[off]) - 1);
200 * Find the highest non-zero bit in the given bitmap, starting at low and
201 * not exceeding size - 1.
204 fd_last_used(struct filedesc *fdp, int low, int size)
206 NDSLOTTYPE *map = fdp->fd_map;
214 if (size % NDENTRIES) {
215 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
216 if ((mask &= map[off]) != 0)
217 return (off * NDENTRIES + flsl(mask) - 1);
220 for (minoff = NDSLOT(low); off >= minoff; --off)
222 return (off * NDENTRIES + flsl(map[off]) - 1);
227 fdisused(struct filedesc *fdp, int fd)
229 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
230 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
231 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
235 * Mark a file descriptor as used.
238 fdused(struct filedesc *fdp, int fd)
241 FILEDESC_XLOCK_ASSERT(fdp);
242 KASSERT(!fdisused(fdp, fd),
243 ("fd already used"));
245 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
246 if (fd > fdp->fd_lastfile)
247 fdp->fd_lastfile = fd;
248 if (fd == fdp->fd_freefile)
249 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
253 * Mark a file descriptor as unused.
256 fdunused(struct filedesc *fdp, int fd)
259 FILEDESC_XLOCK_ASSERT(fdp);
260 KASSERT(fdisused(fdp, fd),
261 ("fd is already unused"));
262 KASSERT(fdp->fd_ofiles[fd] == NULL,
263 ("fd is still in use"));
265 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
266 if (fd < fdp->fd_freefile)
267 fdp->fd_freefile = fd;
268 if (fd == fdp->fd_lastfile)
269 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
273 * System calls on descriptors.
275 #ifndef _SYS_SYSPROTO_H_
276 struct getdtablesize_args {
282 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
284 struct proc *p = td->td_proc;
288 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
294 * Duplicate a file descriptor to a particular value.
296 * Note: keep in mind that a potential race condition exists when closing
297 * descriptors from a shared descriptor table (via rfork).
299 #ifndef _SYS_SYSPROTO_H_
307 dup2(struct thread *td, struct dup2_args *uap)
310 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
315 * Duplicate a file descriptor.
317 #ifndef _SYS_SYSPROTO_H_
324 dup(struct thread *td, struct dup_args *uap)
327 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
331 * The file control system call.
333 #ifndef _SYS_SYSPROTO_H_
342 fcntl(struct thread *td, struct fcntl_args *uap)
357 * Convert old flock structure to new.
359 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
360 fl.l_start = ofl.l_start;
361 fl.l_len = ofl.l_len;
362 fl.l_pid = ofl.l_pid;
363 fl.l_type = ofl.l_type;
364 fl.l_whence = ofl.l_whence;
384 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
393 error = kern_fcntl(td, uap->fd, cmd, arg);
396 if (uap->cmd == F_OGETLK) {
397 ofl.l_start = fl.l_start;
398 ofl.l_len = fl.l_len;
399 ofl.l_pid = fl.l_pid;
400 ofl.l_type = fl.l_type;
401 ofl.l_whence = fl.l_whence;
402 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
403 } else if (uap->cmd == F_GETLK) {
404 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
409 static inline struct file *
410 fdtofp(int fd, struct filedesc *fdp)
414 FILEDESC_LOCK_ASSERT(fdp);
415 if ((unsigned)fd >= fdp->fd_nfiles ||
416 (fp = fdp->fd_ofiles[fd]) == NULL)
422 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
424 struct filedesc *fdp;
444 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
447 case F_DUPFD_CLOEXEC:
449 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
455 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
458 case F_DUP2FD_CLOEXEC:
460 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
466 if ((fp = fdtofp(fd, fdp)) == NULL) {
467 FILEDESC_SUNLOCK(fdp);
471 pop = &fdp->fd_ofileflags[fd];
472 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
473 FILEDESC_SUNLOCK(fdp);
478 if ((fp = fdtofp(fd, fdp)) == NULL) {
479 FILEDESC_XUNLOCK(fdp);
483 pop = &fdp->fd_ofileflags[fd];
484 *pop = (*pop &~ UF_EXCLOSE) |
485 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
486 FILEDESC_XUNLOCK(fdp);
491 if ((fp = fdtofp(fd, fdp)) == NULL) {
492 FILEDESC_SUNLOCK(fdp);
496 td->td_retval[0] = OFLAGS(fp->f_flag);
497 FILEDESC_SUNLOCK(fdp);
502 if ((fp = fdtofp(fd, fdp)) == NULL) {
503 FILEDESC_SUNLOCK(fdp);
508 FILEDESC_SUNLOCK(fdp);
510 tmp = flg = fp->f_flag;
512 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
513 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
514 tmp = fp->f_flag & FNONBLOCK;
515 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
520 tmp = fp->f_flag & FASYNC;
521 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
526 atomic_clear_int(&fp->f_flag, FNONBLOCK);
528 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
534 if ((fp = fdtofp(fd, fdp)) == NULL) {
535 FILEDESC_SUNLOCK(fdp);
540 FILEDESC_SUNLOCK(fdp);
541 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
543 td->td_retval[0] = tmp;
549 if ((fp = fdtofp(fd, fdp)) == NULL) {
550 FILEDESC_SUNLOCK(fdp);
555 FILEDESC_SUNLOCK(fdp);
557 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
562 error = priv_check(td, PRIV_NFS_LOCKD);
570 /* FALLTHROUGH F_SETLK */
575 if ((fp = fdtofp(fd, fdp)) == NULL) {
576 FILEDESC_SUNLOCK(fdp);
580 if (fp->f_type != DTYPE_VNODE) {
581 FILEDESC_SUNLOCK(fdp);
585 flp = (struct flock *)arg;
586 if (flp->l_whence == SEEK_CUR) {
587 if (fp->f_offset < 0 ||
589 fp->f_offset > OFF_MAX - flp->l_start)) {
590 FILEDESC_SUNLOCK(fdp);
594 flp->l_start += fp->f_offset;
598 * VOP_ADVLOCK() may block.
601 FILEDESC_SUNLOCK(fdp);
603 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
604 switch (flp->l_type) {
606 if ((fp->f_flag & FREAD) == 0) {
610 PROC_LOCK(p->p_leader);
611 p->p_leader->p_flag |= P_ADVLOCK;
612 PROC_UNLOCK(p->p_leader);
613 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
617 if ((fp->f_flag & FWRITE) == 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 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
633 * Temporary api for testing remote lock
636 if (flg != F_REMOTE) {
640 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
641 F_UNLCKSYS, flp, flg);
647 VFS_UNLOCK_GIANT(vfslocked);
649 /* Check for race with close */
651 if ((unsigned) fd >= fdp->fd_nfiles ||
652 fp != fdp->fd_ofiles[fd]) {
653 FILEDESC_SUNLOCK(fdp);
654 flp->l_whence = SEEK_SET;
657 flp->l_type = F_UNLCK;
658 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
659 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
660 F_UNLCK, flp, F_POSIX);
661 VFS_UNLOCK_GIANT(vfslocked);
664 FILEDESC_SUNLOCK(fdp);
670 if ((fp = fdtofp(fd, fdp)) == NULL) {
671 FILEDESC_SUNLOCK(fdp);
675 if (fp->f_type != DTYPE_VNODE) {
676 FILEDESC_SUNLOCK(fdp);
680 flp = (struct flock *)arg;
681 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
682 flp->l_type != F_UNLCK) {
683 FILEDESC_SUNLOCK(fdp);
687 if (flp->l_whence == SEEK_CUR) {
688 if ((flp->l_start > 0 &&
689 fp->f_offset > OFF_MAX - flp->l_start) ||
691 fp->f_offset < OFF_MIN - flp->l_start)) {
692 FILEDESC_SUNLOCK(fdp);
696 flp->l_start += fp->f_offset;
699 * VOP_ADVLOCK() may block.
702 FILEDESC_SUNLOCK(fdp);
704 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
705 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
707 VFS_UNLOCK_GIANT(vfslocked);
713 arg = arg ? 128 * 1024: 0;
717 if ((fp = fdtofp(fd, fdp)) == NULL) {
718 FILEDESC_SUNLOCK(fdp);
722 if (fp->f_type != DTYPE_VNODE) {
723 FILEDESC_SUNLOCK(fdp);
728 FILEDESC_SUNLOCK(fdp);
731 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
732 error = vn_lock(vp, LK_SHARED);
734 goto readahead_vnlock_fail;
735 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
737 fp->f_seqcount = (arg + bsize - 1) / bsize;
739 new = old = fp->f_flag;
741 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
742 readahead_vnlock_fail:
743 VFS_UNLOCK_GIANT(vfslocked);
747 new = old = fp->f_flag;
749 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
758 VFS_UNLOCK_GIANT(vfslocked);
763 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
766 do_dup(struct thread *td, int flags, int old, int new,
769 struct filedesc *fdp;
773 int error, holdleaders, maxfd;
779 * Verify we have a valid descriptor to dup from and possibly to
780 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
781 * return EINVAL when the new descriptor is out of bounds.
786 return (flags & DUP_FCNTL ? EINVAL : EBADF);
788 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
791 return (flags & DUP_FCNTL ? EINVAL : EBADF);
794 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
795 FILEDESC_XUNLOCK(fdp);
798 if (flags & DUP_FIXED && old == new) {
800 if (flags & DUP_CLOEXEC)
801 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
802 FILEDESC_XUNLOCK(fdp);
805 fp = fdp->fd_ofiles[old];
809 * If the caller specified a file descriptor, make sure the file
810 * table is large enough to hold it, and grab it. Otherwise, just
811 * allocate a new descriptor the usual way. Since the filedesc
812 * lock may be temporarily dropped in the process, we have to look
815 if (flags & DUP_FIXED) {
816 if (new >= fdp->fd_nfiles)
817 fdgrowtable(fdp, new + 1);
818 if (fdp->fd_ofiles[new] == NULL)
821 if ((error = fdalloc(td, new, &new)) != 0) {
822 FILEDESC_XUNLOCK(fdp);
829 * If the old file changed out from under us then treat it as a
830 * bad file descriptor. Userland should do its own locking to
833 if (fdp->fd_ofiles[old] != fp) {
834 /* we've allocated a descriptor which we won't use */
835 if (fdp->fd_ofiles[new] == NULL)
837 FILEDESC_XUNLOCK(fdp);
842 ("new fd is same as old"));
845 * Save info on the descriptor being overwritten. We cannot close
846 * it without introducing an ownership race for the slot, since we
847 * need to drop the filedesc lock to call closef().
849 * XXX this duplicates parts of close().
851 delfp = fdp->fd_ofiles[new];
854 if (td->td_proc->p_fdtol != NULL) {
856 * Ask fdfree() to sleep to ensure that all relevant
857 * process leaders can be traversed in closef().
859 fdp->fd_holdleaderscount++;
865 * Duplicate the source descriptor
867 fdp->fd_ofiles[new] = fp;
868 if ((flags & DUP_CLOEXEC) != 0)
869 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
871 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
872 if (new > fdp->fd_lastfile)
873 fdp->fd_lastfile = new;
877 * If we dup'd over a valid file, we now own the reference to it
878 * and must dispose of it using closef() semantics (as if a
879 * close() were performed on it).
881 * XXX this duplicates parts of close().
884 knote_fdclose(td, new);
885 if (delfp->f_type == DTYPE_MQUEUE)
886 mq_fdclose(td, new, delfp);
887 FILEDESC_XUNLOCK(fdp);
888 (void) closef(delfp, td);
891 fdp->fd_holdleaderscount--;
892 if (fdp->fd_holdleaderscount == 0 &&
893 fdp->fd_holdleaderswakeup != 0) {
894 fdp->fd_holdleaderswakeup = 0;
895 wakeup(&fdp->fd_holdleaderscount);
897 FILEDESC_XUNLOCK(fdp);
900 FILEDESC_XUNLOCK(fdp);
906 * If sigio is on the list associated with a process or process group,
907 * disable signalling from the device, remove sigio from the list and
911 funsetown(struct sigio **sigiop)
921 *(sigio->sio_myref) = NULL;
922 if ((sigio)->sio_pgid < 0) {
923 struct pgrp *pg = (sigio)->sio_pgrp;
925 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
929 struct proc *p = (sigio)->sio_proc;
931 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
936 crfree(sigio->sio_ucred);
937 free(sigio, M_SIGIO);
941 * Free a list of sigio structures.
942 * We only need to lock the SIGIO_LOCK because we have made ourselves
943 * inaccessible to callers of fsetown and therefore do not need to lock
944 * the proc or pgrp struct for the list manipulation.
947 funsetownlst(struct sigiolst *sigiolst)
953 sigio = SLIST_FIRST(sigiolst);
960 * Every entry of the list should belong
961 * to a single proc or pgrp.
963 if (sigio->sio_pgid < 0) {
964 pg = sigio->sio_pgrp;
965 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
966 } else /* if (sigio->sio_pgid > 0) */ {
968 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
972 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
973 *(sigio->sio_myref) = NULL;
975 KASSERT(sigio->sio_pgid < 0,
976 ("Proc sigio in pgrp sigio list"));
977 KASSERT(sigio->sio_pgrp == pg,
978 ("Bogus pgrp in sigio list"));
980 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
983 } else /* if (p != NULL) */ {
984 KASSERT(sigio->sio_pgid > 0,
985 ("Pgrp sigio in proc sigio list"));
986 KASSERT(sigio->sio_proc == p,
987 ("Bogus proc in sigio list"));
989 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
994 crfree(sigio->sio_ucred);
995 free(sigio, M_SIGIO);
1002 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1004 * After permission checking, add a sigio structure to the sigio list for
1005 * the process or process group.
1008 fsetown(pid_t pgid, struct sigio **sigiop)
1012 struct sigio *sigio;
1022 /* Allocate and fill in the new sigio out of locks. */
1023 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1024 sigio->sio_pgid = pgid;
1025 sigio->sio_ucred = crhold(curthread->td_ucred);
1026 sigio->sio_myref = sigiop;
1028 sx_slock(&proctree_lock);
1037 * Policy - Don't allow a process to FSETOWN a process
1038 * in another session.
1040 * Remove this test to allow maximum flexibility or
1041 * restrict FSETOWN to the current process or process
1042 * group for maximum safety.
1045 if (proc->p_session != curthread->td_proc->p_session) {
1051 } else /* if (pgid < 0) */ {
1052 pgrp = pgfind(-pgid);
1060 * Policy - Don't allow a process to FSETOWN a process
1061 * in another session.
1063 * Remove this test to allow maximum flexibility or
1064 * restrict FSETOWN to the current process or process
1065 * group for maximum safety.
1067 if (pgrp->pg_session != curthread->td_proc->p_session) {
1078 * Since funsetownlst() is called without the proctree
1079 * locked, we need to check for P_WEXIT.
1080 * XXX: is ESRCH correct?
1082 if ((proc->p_flag & P_WEXIT) != 0) {
1087 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1088 sigio->sio_proc = proc;
1092 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1093 sigio->sio_pgrp = pgrp;
1096 sx_sunlock(&proctree_lock);
1103 sx_sunlock(&proctree_lock);
1104 crfree(sigio->sio_ucred);
1105 free(sigio, M_SIGIO);
1110 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1114 struct sigio **sigiop;
1119 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1125 * Close a file descriptor.
1127 #ifndef _SYS_SYSPROTO_H_
1136 struct close_args *uap;
1139 return (kern_close(td, uap->fd));
1147 struct filedesc *fdp;
1154 fdp = td->td_proc->p_fd;
1156 AUDIT_SYSCLOSE(td, fd);
1158 FILEDESC_XLOCK(fdp);
1159 if ((unsigned)fd >= fdp->fd_nfiles ||
1160 (fp = fdp->fd_ofiles[fd]) == NULL) {
1161 FILEDESC_XUNLOCK(fdp);
1164 fdp->fd_ofiles[fd] = NULL;
1165 fdp->fd_ofileflags[fd] = 0;
1167 if (td->td_proc->p_fdtol != NULL) {
1169 * Ask fdfree() to sleep to ensure that all relevant
1170 * process leaders can be traversed in closef().
1172 fdp->fd_holdleaderscount++;
1177 * We now hold the fp reference that used to be owned by the
1178 * descriptor array. We have to unlock the FILEDESC *AFTER*
1179 * knote_fdclose to prevent a race of the fd getting opened, a knote
1180 * added, and deleteing a knote for the new fd.
1182 knote_fdclose(td, fd);
1183 if (fp->f_type == DTYPE_MQUEUE)
1184 mq_fdclose(td, fd, fp);
1185 FILEDESC_XUNLOCK(fdp);
1187 error = closef(fp, td);
1189 FILEDESC_XLOCK(fdp);
1190 fdp->fd_holdleaderscount--;
1191 if (fdp->fd_holdleaderscount == 0 &&
1192 fdp->fd_holdleaderswakeup != 0) {
1193 fdp->fd_holdleaderswakeup = 0;
1194 wakeup(&fdp->fd_holdleaderscount);
1196 FILEDESC_XUNLOCK(fdp);
1202 * Close open file descriptors.
1204 #ifndef _SYS_SYSPROTO_H_
1205 struct closefrom_args {
1211 closefrom(struct thread *td, struct closefrom_args *uap)
1213 struct filedesc *fdp;
1216 fdp = td->td_proc->p_fd;
1217 AUDIT_ARG_FD(uap->lowfd);
1220 * Treat negative starting file descriptor values identical to
1221 * closefrom(0) which closes all files.
1225 FILEDESC_SLOCK(fdp);
1226 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1227 if (fdp->fd_ofiles[fd] != NULL) {
1228 FILEDESC_SUNLOCK(fdp);
1229 (void)kern_close(td, fd);
1230 FILEDESC_SLOCK(fdp);
1233 FILEDESC_SUNLOCK(fdp);
1237 #if defined(COMPAT_43)
1239 * Return status information about a file descriptor.
1241 #ifndef _SYS_SYSPROTO_H_
1242 struct ofstat_args {
1249 ofstat(struct thread *td, struct ofstat_args *uap)
1255 error = kern_fstat(td, uap->fd, &ub);
1258 error = copyout(&oub, uap->sb, sizeof(oub));
1262 #endif /* COMPAT_43 */
1265 * Return status information about a file descriptor.
1267 #ifndef _SYS_SYSPROTO_H_
1275 fstat(struct thread *td, struct fstat_args *uap)
1280 error = kern_fstat(td, uap->fd, &ub);
1282 error = copyout(&ub, uap->sb, sizeof(ub));
1287 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1294 if ((error = fget(td, fd, &fp)) != 0)
1297 AUDIT_ARG_FILE(td->td_proc, fp);
1299 error = fo_stat(fp, sbp, td->td_ucred, td);
1302 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1309 * Return status information about a file descriptor.
1311 #ifndef _SYS_SYSPROTO_H_
1312 struct nfstat_args {
1319 nfstat(struct thread *td, struct nfstat_args *uap)
1325 error = kern_fstat(td, uap->fd, &ub);
1327 cvtnstat(&ub, &nub);
1328 error = copyout(&nub, uap->sb, sizeof(nub));
1334 * Return pathconf information about a file descriptor.
1336 #ifndef _SYS_SYSPROTO_H_
1337 struct fpathconf_args {
1344 fpathconf(struct thread *td, struct fpathconf_args *uap)
1350 if ((error = fget(td, uap->fd, &fp)) != 0)
1353 /* If asynchronous I/O is available, it works for all descriptors. */
1354 if (uap->name == _PC_ASYNC_IO) {
1355 td->td_retval[0] = async_io_version;
1361 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1362 vn_lock(vp, LK_SHARED | LK_RETRY);
1363 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1365 VFS_UNLOCK_GIANT(vfslocked);
1366 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1367 if (uap->name != _PC_PIPE_BUF) {
1370 td->td_retval[0] = PIPE_BUF;
1382 * Grow the file table to accomodate (at least) nfd descriptors. This may
1383 * block and drop the filedesc lock, but it will reacquire it before
1387 fdgrowtable(struct filedesc *fdp, int nfd)
1389 struct filedesc0 *fdp0;
1390 struct freetable *fo;
1391 struct file **ntable;
1392 struct file **otable;
1394 int nnfiles, onfiles;
1397 FILEDESC_XLOCK_ASSERT(fdp);
1399 KASSERT(fdp->fd_nfiles > 0,
1400 ("zero-length file table"));
1402 /* compute the size of the new table */
1403 onfiles = fdp->fd_nfiles;
1404 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1405 if (nnfiles <= onfiles)
1406 /* the table is already large enough */
1409 /* allocate a new table and (if required) new bitmaps */
1410 FILEDESC_XUNLOCK(fdp);
1411 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1412 M_FILEDESC, M_ZERO | M_WAITOK);
1413 nfileflags = (char *)&ntable[nnfiles];
1414 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1415 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1416 M_FILEDESC, M_ZERO | M_WAITOK);
1419 FILEDESC_XLOCK(fdp);
1422 * We now have new tables ready to go. Since we dropped the
1423 * filedesc lock to call malloc(), watch out for a race.
1425 onfiles = fdp->fd_nfiles;
1426 if (onfiles >= nnfiles) {
1427 /* we lost the race, but that's OK */
1428 free(ntable, M_FILEDESC);
1430 free(nmap, M_FILEDESC);
1433 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1434 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1435 otable = fdp->fd_ofiles;
1436 fdp->fd_ofileflags = nfileflags;
1437 fdp->fd_ofiles = ntable;
1439 * We must preserve ofiles until the process exits because we can't
1440 * be certain that no threads have references to the old table via
1443 if (onfiles > NDFILE) {
1444 fo = (struct freetable *)&otable[onfiles];
1445 fdp0 = (struct filedesc0 *)fdp;
1446 fo->ft_table = otable;
1447 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1449 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1450 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1451 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1452 free(fdp->fd_map, M_FILEDESC);
1455 fdp->fd_nfiles = nnfiles;
1459 * Allocate a file descriptor for the process.
1462 fdalloc(struct thread *td, int minfd, int *result)
1464 struct proc *p = td->td_proc;
1465 struct filedesc *fdp = p->p_fd;
1468 FILEDESC_XLOCK_ASSERT(fdp);
1470 if (fdp->fd_freefile > minfd)
1471 minfd = fdp->fd_freefile;
1474 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1478 * Search the bitmap for a free descriptor. If none is found, try
1479 * to grow the file table. Keep at it until we either get a file
1480 * descriptor or run into process or system limits; fdgrowtable()
1481 * may drop the filedesc lock, so we're in a race.
1484 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1487 if (fd < fdp->fd_nfiles)
1489 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1493 * Perform some sanity checks, then mark the file descriptor as
1494 * used and return it to the caller.
1496 KASSERT(!fdisused(fdp, fd),
1497 ("fd_first_free() returned non-free descriptor"));
1498 KASSERT(fdp->fd_ofiles[fd] == NULL,
1499 ("free descriptor isn't"));
1500 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1507 * Check to see whether n user file descriptors are available to the process
1511 fdavail(struct thread *td, int n)
1513 struct proc *p = td->td_proc;
1514 struct filedesc *fdp = td->td_proc->p_fd;
1518 FILEDESC_LOCK_ASSERT(fdp);
1521 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1523 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1525 last = min(fdp->fd_nfiles, lim);
1526 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1527 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1528 if (*fpp == NULL && --n <= 0)
1535 * Create a new open file structure and allocate a file decriptor for the
1536 * process that refers to it. We add one reference to the file for the
1537 * descriptor table and one reference for resultfp. This is to prevent us
1538 * being preempted and the entry in the descriptor table closed after we
1539 * release the FILEDESC lock.
1542 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1544 struct proc *p = td->td_proc;
1547 int maxuserfiles = maxfiles - (maxfiles / 20);
1548 static struct timeval lastfail;
1551 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1552 if ((openfiles >= maxuserfiles &&
1553 priv_check(td, PRIV_MAXFILES) != 0) ||
1554 openfiles >= maxfiles) {
1555 if (ppsratecheck(&lastfail, &curfail, 1)) {
1556 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1557 td->td_ucred->cr_ruid);
1559 uma_zfree(file_zone, fp);
1562 atomic_add_int(&openfiles, 1);
1565 * If the process has file descriptor zero open, add the new file
1566 * descriptor to the list of open files at that point, otherwise
1567 * put it at the front of the list of open files.
1569 refcount_init(&fp->f_count, 1);
1572 fp->f_cred = crhold(td->td_ucred);
1573 fp->f_ops = &badfileops;
1576 FILEDESC_XLOCK(p->p_fd);
1577 if ((error = fdalloc(td, 0, &i))) {
1578 FILEDESC_XUNLOCK(p->p_fd);
1584 p->p_fd->fd_ofiles[i] = fp;
1585 if ((flags & O_CLOEXEC) != 0)
1586 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1587 FILEDESC_XUNLOCK(p->p_fd);
1596 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1599 return (fallocf(td, resultfp, resultfd, 0));
1603 * Build a new filedesc structure from another.
1604 * Copy the current, root, and jail root vnode references.
1607 fdinit(struct filedesc *fdp)
1609 struct filedesc0 *newfdp;
1611 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1612 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1614 FILEDESC_XLOCK(fdp);
1615 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1616 if (newfdp->fd_fd.fd_cdir)
1617 VREF(newfdp->fd_fd.fd_cdir);
1618 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1619 if (newfdp->fd_fd.fd_rdir)
1620 VREF(newfdp->fd_fd.fd_rdir);
1621 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1622 if (newfdp->fd_fd.fd_jdir)
1623 VREF(newfdp->fd_fd.fd_jdir);
1624 FILEDESC_XUNLOCK(fdp);
1627 /* Create the file descriptor table. */
1628 newfdp->fd_fd.fd_refcnt = 1;
1629 newfdp->fd_fd.fd_holdcnt = 1;
1630 newfdp->fd_fd.fd_cmask = CMASK;
1631 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1632 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1633 newfdp->fd_fd.fd_nfiles = NDFILE;
1634 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1635 newfdp->fd_fd.fd_lastfile = -1;
1636 return (&newfdp->fd_fd);
1639 static struct filedesc *
1640 fdhold(struct proc *p)
1642 struct filedesc *fdp;
1644 mtx_lock(&fdesc_mtx);
1648 mtx_unlock(&fdesc_mtx);
1653 fddrop(struct filedesc *fdp)
1655 struct filedesc0 *fdp0;
1656 struct freetable *ft;
1659 mtx_lock(&fdesc_mtx);
1660 i = --fdp->fd_holdcnt;
1661 mtx_unlock(&fdesc_mtx);
1665 FILEDESC_LOCK_DESTROY(fdp);
1666 fdp0 = (struct filedesc0 *)fdp;
1667 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1668 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1669 free(ft->ft_table, M_FILEDESC);
1671 free(fdp, M_FILEDESC);
1675 * Share a filedesc structure.
1678 fdshare(struct filedesc *fdp)
1681 FILEDESC_XLOCK(fdp);
1683 FILEDESC_XUNLOCK(fdp);
1688 * Unshare a filedesc structure, if necessary by making a copy
1691 fdunshare(struct proc *p, struct thread *td)
1694 FILEDESC_XLOCK(p->p_fd);
1695 if (p->p_fd->fd_refcnt > 1) {
1696 struct filedesc *tmp;
1698 FILEDESC_XUNLOCK(p->p_fd);
1699 tmp = fdcopy(p->p_fd);
1703 FILEDESC_XUNLOCK(p->p_fd);
1707 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1708 * this is to ease callers, not catch errors.
1711 fdcopy(struct filedesc *fdp)
1713 struct filedesc *newfdp;
1716 /* Certain daemons might not have file descriptors. */
1720 newfdp = fdinit(fdp);
1721 FILEDESC_SLOCK(fdp);
1722 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1723 FILEDESC_SUNLOCK(fdp);
1724 FILEDESC_XLOCK(newfdp);
1725 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1726 FILEDESC_XUNLOCK(newfdp);
1727 FILEDESC_SLOCK(fdp);
1729 /* copy everything except kqueue descriptors */
1730 newfdp->fd_freefile = -1;
1731 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1732 if (fdisused(fdp, i) &&
1733 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1734 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1735 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1736 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1737 fhold(newfdp->fd_ofiles[i]);
1738 newfdp->fd_lastfile = i;
1740 if (newfdp->fd_freefile == -1)
1741 newfdp->fd_freefile = i;
1744 newfdp->fd_cmask = fdp->fd_cmask;
1745 FILEDESC_SUNLOCK(fdp);
1746 FILEDESC_XLOCK(newfdp);
1747 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1748 if (newfdp->fd_ofiles[i] != NULL)
1750 if (newfdp->fd_freefile == -1)
1751 newfdp->fd_freefile = i;
1752 FILEDESC_XUNLOCK(newfdp);
1757 * Release a filedesc structure.
1760 fdfree(struct thread *td)
1762 struct filedesc *fdp;
1765 struct filedesc_to_leader *fdtol;
1767 struct vnode *cdir, *jdir, *rdir, *vp;
1770 /* Certain daemons might not have file descriptors. */
1771 fdp = td->td_proc->p_fd;
1775 /* Check for special need to clear POSIX style locks */
1776 fdtol = td->td_proc->p_fdtol;
1777 if (fdtol != NULL) {
1778 FILEDESC_XLOCK(fdp);
1779 KASSERT(fdtol->fdl_refcount > 0,
1780 ("filedesc_to_refcount botch: fdl_refcount=%d",
1781 fdtol->fdl_refcount));
1782 if (fdtol->fdl_refcount == 1 &&
1783 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1784 for (i = 0, fpp = fdp->fd_ofiles;
1785 i <= fdp->fd_lastfile;
1788 (*fpp)->f_type != DTYPE_VNODE)
1792 FILEDESC_XUNLOCK(fdp);
1793 lf.l_whence = SEEK_SET;
1796 lf.l_type = F_UNLCK;
1798 locked = VFS_LOCK_GIANT(vp->v_mount);
1799 (void) VOP_ADVLOCK(vp,
1800 (caddr_t)td->td_proc->
1805 VFS_UNLOCK_GIANT(locked);
1806 FILEDESC_XLOCK(fdp);
1808 fpp = fdp->fd_ofiles + i;
1812 if (fdtol->fdl_refcount == 1) {
1813 if (fdp->fd_holdleaderscount > 0 &&
1814 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1816 * close() or do_dup() has cleared a reference
1817 * in a shared file descriptor table.
1819 fdp->fd_holdleaderswakeup = 1;
1820 sx_sleep(&fdp->fd_holdleaderscount,
1821 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1824 if (fdtol->fdl_holdcount > 0) {
1826 * Ensure that fdtol->fdl_leader remains
1827 * valid in closef().
1829 fdtol->fdl_wakeup = 1;
1830 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1835 fdtol->fdl_refcount--;
1836 if (fdtol->fdl_refcount == 0 &&
1837 fdtol->fdl_holdcount == 0) {
1838 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1839 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1842 td->td_proc->p_fdtol = NULL;
1843 FILEDESC_XUNLOCK(fdp);
1845 free(fdtol, M_FILEDESC_TO_LEADER);
1847 FILEDESC_XLOCK(fdp);
1848 i = --fdp->fd_refcnt;
1849 FILEDESC_XUNLOCK(fdp);
1853 fpp = fdp->fd_ofiles;
1854 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1856 FILEDESC_XLOCK(fdp);
1859 FILEDESC_XUNLOCK(fdp);
1860 (void) closef(fp, td);
1863 FILEDESC_XLOCK(fdp);
1865 /* XXX This should happen earlier. */
1866 mtx_lock(&fdesc_mtx);
1867 td->td_proc->p_fd = NULL;
1868 mtx_unlock(&fdesc_mtx);
1870 if (fdp->fd_nfiles > NDFILE)
1871 free(fdp->fd_ofiles, M_FILEDESC);
1872 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1873 free(fdp->fd_map, M_FILEDESC);
1877 cdir = fdp->fd_cdir;
1878 fdp->fd_cdir = NULL;
1879 rdir = fdp->fd_rdir;
1880 fdp->fd_rdir = NULL;
1881 jdir = fdp->fd_jdir;
1882 fdp->fd_jdir = NULL;
1883 FILEDESC_XUNLOCK(fdp);
1886 locked = VFS_LOCK_GIANT(cdir->v_mount);
1888 VFS_UNLOCK_GIANT(locked);
1891 locked = VFS_LOCK_GIANT(rdir->v_mount);
1893 VFS_UNLOCK_GIANT(locked);
1896 locked = VFS_LOCK_GIANT(jdir->v_mount);
1898 VFS_UNLOCK_GIANT(locked);
1905 * For setugid programs, we don't want to people to use that setugidness
1906 * to generate error messages which write to a file which otherwise would
1907 * otherwise be off-limits to the process. We check for filesystems where
1908 * the vnode can change out from under us after execve (like [lin]procfs).
1910 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1911 * sufficient. We also don't check for setugidness since we know we are.
1914 is_unsafe(struct file *fp)
1916 if (fp->f_type == DTYPE_VNODE) {
1917 struct vnode *vp = fp->f_vnode;
1919 if ((vp->v_vflag & VV_PROCDEP) != 0)
1926 * Make this setguid thing safe, if at all possible.
1929 setugidsafety(struct thread *td)
1931 struct filedesc *fdp;
1934 /* Certain daemons might not have file descriptors. */
1935 fdp = td->td_proc->p_fd;
1940 * Note: fdp->fd_ofiles may be reallocated out from under us while
1941 * we are blocked in a close. Be careful!
1943 FILEDESC_XLOCK(fdp);
1944 for (i = 0; i <= fdp->fd_lastfile; i++) {
1947 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1950 knote_fdclose(td, i);
1952 * NULL-out descriptor prior to close to avoid
1953 * a race while close blocks.
1955 fp = fdp->fd_ofiles[i];
1956 fdp->fd_ofiles[i] = NULL;
1957 fdp->fd_ofileflags[i] = 0;
1959 FILEDESC_XUNLOCK(fdp);
1960 (void) closef(fp, td);
1961 FILEDESC_XLOCK(fdp);
1964 FILEDESC_XUNLOCK(fdp);
1968 * If a specific file object occupies a specific file descriptor, close the
1969 * file descriptor entry and drop a reference on the file object. This is a
1970 * convenience function to handle a subsequent error in a function that calls
1971 * falloc() that handles the race that another thread might have closed the
1972 * file descriptor out from under the thread creating the file object.
1975 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1978 FILEDESC_XLOCK(fdp);
1979 if (fdp->fd_ofiles[idx] == fp) {
1980 fdp->fd_ofiles[idx] = NULL;
1982 FILEDESC_XUNLOCK(fdp);
1985 FILEDESC_XUNLOCK(fdp);
1989 * Close any files on exec?
1992 fdcloseexec(struct thread *td)
1994 struct filedesc *fdp;
1997 /* Certain daemons might not have file descriptors. */
1998 fdp = td->td_proc->p_fd;
2002 FILEDESC_XLOCK(fdp);
2005 * We cannot cache fd_ofiles or fd_ofileflags since operations
2006 * may block and rip them out from under us.
2008 for (i = 0; i <= fdp->fd_lastfile; i++) {
2009 if (fdp->fd_ofiles[i] != NULL &&
2010 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2011 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2014 knote_fdclose(td, i);
2016 * NULL-out descriptor prior to close to avoid
2017 * a race while close blocks.
2019 fp = fdp->fd_ofiles[i];
2020 fdp->fd_ofiles[i] = NULL;
2021 fdp->fd_ofileflags[i] = 0;
2023 if (fp->f_type == DTYPE_MQUEUE)
2024 mq_fdclose(td, i, fp);
2025 FILEDESC_XUNLOCK(fdp);
2026 (void) closef(fp, td);
2027 FILEDESC_XLOCK(fdp);
2030 FILEDESC_XUNLOCK(fdp);
2034 * It is unsafe for set[ug]id processes to be started with file
2035 * descriptors 0..2 closed, as these descriptors are given implicit
2036 * significance in the Standard C library. fdcheckstd() will create a
2037 * descriptor referencing /dev/null for each of stdin, stdout, and
2038 * stderr that is not already open.
2041 fdcheckstd(struct thread *td)
2043 struct filedesc *fdp;
2044 register_t retval, save;
2045 int i, error, devnull;
2047 fdp = td->td_proc->p_fd;
2050 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2053 for (i = 0; i < 3; i++) {
2054 if (fdp->fd_ofiles[i] != NULL)
2057 save = td->td_retval[0];
2058 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2060 devnull = td->td_retval[0];
2061 td->td_retval[0] = save;
2064 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2066 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2075 * Internal form of close. Decrement reference count on file structure.
2076 * Note: td may be NULL when closing a file that was being passed in a
2079 * XXXRW: Giant is not required for the caller, but often will be held; this
2080 * makes it moderately likely the Giant will be recursed in the VFS case.
2083 closef(struct file *fp, struct thread *td)
2087 struct filedesc_to_leader *fdtol;
2088 struct filedesc *fdp;
2091 * POSIX record locking dictates that any close releases ALL
2092 * locks owned by this process. This is handled by setting
2093 * a flag in the unlock to free ONLY locks obeying POSIX
2094 * semantics, and not to free BSD-style file locks.
2095 * If the descriptor was in a message, POSIX-style locks
2096 * aren't passed with the descriptor, and the thread pointer
2097 * will be NULL. Callers should be careful only to pass a
2098 * NULL thread pointer when there really is no owning
2099 * context that might have locks, or the locks will be
2102 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2106 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2107 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2108 lf.l_whence = SEEK_SET;
2111 lf.l_type = F_UNLCK;
2112 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2113 F_UNLCK, &lf, F_POSIX);
2115 fdtol = td->td_proc->p_fdtol;
2116 if (fdtol != NULL) {
2118 * Handle special case where file descriptor table is
2119 * shared between multiple process leaders.
2121 fdp = td->td_proc->p_fd;
2122 FILEDESC_XLOCK(fdp);
2123 for (fdtol = fdtol->fdl_next;
2124 fdtol != td->td_proc->p_fdtol;
2125 fdtol = fdtol->fdl_next) {
2126 if ((fdtol->fdl_leader->p_flag &
2129 fdtol->fdl_holdcount++;
2130 FILEDESC_XUNLOCK(fdp);
2131 lf.l_whence = SEEK_SET;
2134 lf.l_type = F_UNLCK;
2136 (void) VOP_ADVLOCK(vp,
2137 (caddr_t)fdtol->fdl_leader,
2138 F_UNLCK, &lf, F_POSIX);
2139 FILEDESC_XLOCK(fdp);
2140 fdtol->fdl_holdcount--;
2141 if (fdtol->fdl_holdcount == 0 &&
2142 fdtol->fdl_wakeup != 0) {
2143 fdtol->fdl_wakeup = 0;
2147 FILEDESC_XUNLOCK(fdp);
2149 VFS_UNLOCK_GIANT(vfslocked);
2151 return (fdrop(fp, td));
2155 * Initialize the file pointer with the specified properties.
2157 * The ops are set with release semantics to be certain that the flags, type,
2158 * and data are visible when ops is. This is to prevent ops methods from being
2159 * called with bad data.
2162 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2167 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2171 fget_unlocked(struct filedesc *fdp, int fd)
2176 if (fd < 0 || fd >= fdp->fd_nfiles)
2179 * Fetch the descriptor locklessly. We avoid fdrop() races by
2180 * never raising a refcount above 0. To accomplish this we have
2181 * to use a cmpset loop rather than an atomic_add. The descriptor
2182 * must be re-verified once we acquire a reference to be certain
2183 * that the identity is still correct and we did not lose a race
2184 * due to preemption.
2187 fp = fdp->fd_ofiles[fd];
2190 count = fp->f_count;
2194 * Use an acquire barrier to prevent caching of fd_ofiles
2195 * so it is refreshed for verification.
2197 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2199 if (fp == fdp->fd_ofiles[fd])
2201 fdrop(fp, curthread);
2208 * Extract the file pointer associated with the specified descriptor for the
2209 * current user process.
2211 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2214 * If an error occured the non-zero error is returned and *fpp is set to
2215 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2216 * responsible for fdrop().
2219 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2221 struct filedesc *fdp;
2225 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2227 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2229 if (fp->f_ops == &badfileops) {
2234 * FREAD and FWRITE failure return EBADF as per POSIX.
2236 * Only one flag, or 0, may be specified.
2238 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2239 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2248 fget(struct thread *td, int fd, struct file **fpp)
2251 return(_fget(td, fd, fpp, 0));
2255 fget_read(struct thread *td, int fd, struct file **fpp)
2258 return(_fget(td, fd, fpp, FREAD));
2262 fget_write(struct thread *td, int fd, struct file **fpp)
2265 return(_fget(td, fd, fpp, FWRITE));
2269 * Like fget() but loads the underlying vnode, or returns an error if the
2270 * descriptor does not represent a vnode. Note that pipes use vnodes but
2271 * never have VM objects. The returned vnode will be vref()'d.
2273 * XXX: what about the unused flags ?
2276 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2282 if ((error = _fget(td, fd, &fp, flags)) != 0)
2284 if (fp->f_vnode == NULL) {
2296 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2299 return (_fgetvp(td, fd, vpp, 0));
2303 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2306 return (_fgetvp(td, fd, vpp, FREAD));
2311 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2314 return (_fgetvp(td, fd, vpp, FWRITE));
2319 * Like fget() but loads the underlying socket, or returns an error if the
2320 * descriptor does not represent a socket.
2322 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2325 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2326 * on their file descriptor reference to prevent the socket from being free'd
2330 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2338 if ((error = _fget(td, fd, &fp, 0)) != 0)
2340 if (fp->f_type != DTYPE_SOCKET) {
2345 *fflagp = fp->f_flag;
2356 * Drop the reference count on the socket and XXX release the SX lock in the
2357 * future. The last reference closes the socket.
2359 * Note: fputsock() is deprecated, see comment for fgetsock().
2362 fputsock(struct socket *so)
2367 CURVNET_SET(so->so_vnet);
2373 * Handle the last reference to a file being closed.
2376 _fdrop(struct file *fp, struct thread *td)
2381 if (fp->f_count != 0)
2382 panic("fdrop: count %d", fp->f_count);
2383 if (fp->f_ops != &badfileops)
2384 error = fo_close(fp, td);
2385 atomic_subtract_int(&openfiles, 1);
2387 free(fp->f_advice, M_FADVISE);
2388 uma_zfree(file_zone, fp);
2394 * Apply an advisory lock on a file descriptor.
2396 * Just attempt to get a record lock of the requested type on the entire file
2397 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2399 #ifndef _SYS_SYSPROTO_H_
2407 flock(struct thread *td, struct flock_args *uap)
2415 if ((error = fget(td, uap->fd, &fp)) != 0)
2417 if (fp->f_type != DTYPE_VNODE) {
2419 return (EOPNOTSUPP);
2423 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2424 lf.l_whence = SEEK_SET;
2427 if (uap->how & LOCK_UN) {
2428 lf.l_type = F_UNLCK;
2429 atomic_clear_int(&fp->f_flag, FHASLOCK);
2430 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2433 if (uap->how & LOCK_EX)
2434 lf.l_type = F_WRLCK;
2435 else if (uap->how & LOCK_SH)
2436 lf.l_type = F_RDLCK;
2441 atomic_set_int(&fp->f_flag, FHASLOCK);
2442 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2443 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2446 VFS_UNLOCK_GIANT(vfslocked);
2450 * Duplicate the specified descriptor to a free descriptor.
2453 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2459 * If the to-be-dup'd fd number is greater than the allowed number
2460 * of file descriptors, or the fd to be dup'd has already been
2461 * closed, then reject.
2463 FILEDESC_XLOCK(fdp);
2464 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2465 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2466 FILEDESC_XUNLOCK(fdp);
2471 * There are two cases of interest here.
2473 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2475 * For ENXIO steal away the file structure from (dfd) and store it in
2476 * (indx). (dfd) is effectively closed by this operation.
2478 * Any other error code is just returned.
2483 * Check that the mode the file is being opened for is a
2484 * subset of the mode of the existing descriptor.
2486 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2487 FILEDESC_XUNLOCK(fdp);
2490 fp = fdp->fd_ofiles[indx];
2491 fdp->fd_ofiles[indx] = wfp;
2492 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2496 FILEDESC_XUNLOCK(fdp);
2499 * We now own the reference to fp that the ofiles[]
2500 * array used to own. Release it.
2507 * Steal away the file pointer from dfd and stuff it into indx.
2509 fp = fdp->fd_ofiles[indx];
2510 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2511 fdp->fd_ofiles[dfd] = NULL;
2512 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2513 fdp->fd_ofileflags[dfd] = 0;
2517 FILEDESC_XUNLOCK(fdp);
2520 * We now own the reference to fp that the ofiles[] array
2521 * used to own. Release it.
2528 FILEDESC_XUNLOCK(fdp);
2535 * Scan all active processes and prisons to see if any of them have a current
2536 * or root directory of `olddp'. If so, replace them with the new mount point.
2539 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2541 struct filedesc *fdp;
2546 if (vrefcnt(olddp) == 1)
2549 sx_slock(&allproc_lock);
2550 FOREACH_PROC_IN_SYSTEM(p) {
2554 FILEDESC_XLOCK(fdp);
2555 if (fdp->fd_cdir == olddp) {
2557 fdp->fd_cdir = newdp;
2560 if (fdp->fd_rdir == olddp) {
2562 fdp->fd_rdir = newdp;
2565 if (fdp->fd_jdir == olddp) {
2567 fdp->fd_jdir = newdp;
2570 FILEDESC_XUNLOCK(fdp);
2573 sx_sunlock(&allproc_lock);
2574 if (rootvnode == olddp) {
2579 mtx_lock(&prison0.pr_mtx);
2580 if (prison0.pr_root == olddp) {
2582 prison0.pr_root = newdp;
2585 mtx_unlock(&prison0.pr_mtx);
2586 sx_slock(&allprison_lock);
2587 TAILQ_FOREACH(pr, &allprison, pr_list) {
2588 mtx_lock(&pr->pr_mtx);
2589 if (pr->pr_root == olddp) {
2591 pr->pr_root = newdp;
2594 mtx_unlock(&pr->pr_mtx);
2596 sx_sunlock(&allprison_lock);
2601 struct filedesc_to_leader *
2602 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2604 struct filedesc_to_leader *fdtol;
2606 fdtol = malloc(sizeof(struct filedesc_to_leader),
2607 M_FILEDESC_TO_LEADER,
2609 fdtol->fdl_refcount = 1;
2610 fdtol->fdl_holdcount = 0;
2611 fdtol->fdl_wakeup = 0;
2612 fdtol->fdl_leader = leader;
2614 FILEDESC_XLOCK(fdp);
2615 fdtol->fdl_next = old->fdl_next;
2616 fdtol->fdl_prev = old;
2617 old->fdl_next = fdtol;
2618 fdtol->fdl_next->fdl_prev = fdtol;
2619 FILEDESC_XUNLOCK(fdp);
2621 fdtol->fdl_next = fdtol;
2622 fdtol->fdl_prev = fdtol;
2628 * Get file structures globally.
2631 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2634 struct filedesc *fdp;
2639 error = sysctl_wire_old_buffer(req, 0);
2642 if (req->oldptr == NULL) {
2644 sx_slock(&allproc_lock);
2645 FOREACH_PROC_IN_SYSTEM(p) {
2646 if (p->p_state == PRS_NEW)
2651 /* overestimates sparse tables. */
2652 if (fdp->fd_lastfile > 0)
2653 n += fdp->fd_lastfile;
2656 sx_sunlock(&allproc_lock);
2657 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2660 bzero(&xf, sizeof(xf));
2661 xf.xf_size = sizeof(xf);
2662 sx_slock(&allproc_lock);
2663 FOREACH_PROC_IN_SYSTEM(p) {
2665 if (p->p_state == PRS_NEW) {
2669 if (p_cansee(req->td, p) != 0) {
2673 xf.xf_pid = p->p_pid;
2674 xf.xf_uid = p->p_ucred->cr_uid;
2679 FILEDESC_SLOCK(fdp);
2680 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2681 if ((fp = fdp->fd_ofiles[n]) == NULL)
2685 xf.xf_data = fp->f_data;
2686 xf.xf_vnode = fp->f_vnode;
2687 xf.xf_type = fp->f_type;
2688 xf.xf_count = fp->f_count;
2690 xf.xf_offset = fp->f_offset;
2691 xf.xf_flag = fp->f_flag;
2692 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2696 FILEDESC_SUNLOCK(fdp);
2701 sx_sunlock(&allproc_lock);
2705 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2706 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2708 #ifdef KINFO_OFILE_SIZE
2709 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2712 #ifdef COMPAT_FREEBSD7
2714 export_vnode_for_osysctl(struct vnode *vp, int type,
2715 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2718 char *fullpath, *freepath;
2721 bzero(kif, sizeof(*kif));
2722 kif->kf_structsize = sizeof(*kif);
2726 kif->kf_type = KF_TYPE_VNODE;
2727 /* This function only handles directories. */
2728 if (vp->v_type != VDIR) {
2732 kif->kf_vnode_type = KF_VTYPE_VDIR;
2735 * This is not a true file descriptor, so we set a bogus refcount
2736 * and offset to indicate these fields should be ignored.
2738 kif->kf_ref_count = -1;
2739 kif->kf_offset = -1;
2743 FILEDESC_SUNLOCK(fdp);
2744 vn_fullpath(curthread, vp, &fullpath, &freepath);
2745 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2747 VFS_UNLOCK_GIANT(vfslocked);
2748 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2749 if (freepath != NULL)
2750 free(freepath, M_TEMP);
2751 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2752 FILEDESC_SLOCK(fdp);
2757 * Get per-process file descriptors for use by procstat(1), et al.
2760 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2762 char *fullpath, *freepath;
2763 struct kinfo_ofile *kif;
2764 struct filedesc *fdp;
2765 int error, i, *name;
2766 struct shmfd *shmfd;
2776 if ((p = pfind((pid_t)name[0])) == NULL)
2778 if ((error = p_candebug(curthread, p))) {
2786 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2787 FILEDESC_SLOCK(fdp);
2788 if (fdp->fd_cdir != NULL)
2789 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2791 if (fdp->fd_rdir != NULL)
2792 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2794 if (fdp->fd_jdir != NULL)
2795 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2797 for (i = 0; i < fdp->fd_nfiles; i++) {
2798 if ((fp = fdp->fd_ofiles[i]) == NULL)
2800 bzero(kif, sizeof(*kif));
2801 kif->kf_structsize = sizeof(*kif);
2808 switch (fp->f_type) {
2810 kif->kf_type = KF_TYPE_VNODE;
2815 kif->kf_type = KF_TYPE_SOCKET;
2820 kif->kf_type = KF_TYPE_PIPE;
2824 kif->kf_type = KF_TYPE_FIFO;
2829 kif->kf_type = KF_TYPE_KQUEUE;
2833 kif->kf_type = KF_TYPE_CRYPTO;
2837 kif->kf_type = KF_TYPE_MQUEUE;
2841 kif->kf_type = KF_TYPE_SHM;
2846 kif->kf_type = KF_TYPE_SEM;
2851 kif->kf_type = KF_TYPE_PTS;
2856 kif->kf_type = KF_TYPE_UNKNOWN;
2859 kif->kf_ref_count = fp->f_count;
2860 if (fp->f_flag & FREAD)
2861 kif->kf_flags |= KF_FLAG_READ;
2862 if (fp->f_flag & FWRITE)
2863 kif->kf_flags |= KF_FLAG_WRITE;
2864 if (fp->f_flag & FAPPEND)
2865 kif->kf_flags |= KF_FLAG_APPEND;
2866 if (fp->f_flag & FASYNC)
2867 kif->kf_flags |= KF_FLAG_ASYNC;
2868 if (fp->f_flag & FFSYNC)
2869 kif->kf_flags |= KF_FLAG_FSYNC;
2870 if (fp->f_flag & FNONBLOCK)
2871 kif->kf_flags |= KF_FLAG_NONBLOCK;
2872 if (fp->f_flag & O_DIRECT)
2873 kif->kf_flags |= KF_FLAG_DIRECT;
2874 if (fp->f_flag & FHASLOCK)
2875 kif->kf_flags |= KF_FLAG_HASLOCK;
2876 kif->kf_offset = fp->f_offset;
2879 switch (vp->v_type) {
2881 kif->kf_vnode_type = KF_VTYPE_VNON;
2884 kif->kf_vnode_type = KF_VTYPE_VREG;
2887 kif->kf_vnode_type = KF_VTYPE_VDIR;
2890 kif->kf_vnode_type = KF_VTYPE_VBLK;
2893 kif->kf_vnode_type = KF_VTYPE_VCHR;
2896 kif->kf_vnode_type = KF_VTYPE_VLNK;
2899 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2902 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2905 kif->kf_vnode_type = KF_VTYPE_VBAD;
2908 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2912 * It is OK to drop the filedesc lock here as we will
2913 * re-validate and re-evaluate its properties when
2914 * the loop continues.
2918 FILEDESC_SUNLOCK(fdp);
2919 vn_fullpath(curthread, vp, &fullpath, &freepath);
2920 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2922 VFS_UNLOCK_GIANT(vfslocked);
2923 strlcpy(kif->kf_path, fullpath,
2924 sizeof(kif->kf_path));
2925 if (freepath != NULL)
2926 free(freepath, M_TEMP);
2927 FILEDESC_SLOCK(fdp);
2930 struct sockaddr *sa;
2932 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2933 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2934 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2937 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2938 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2939 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2942 kif->kf_sock_domain =
2943 so->so_proto->pr_domain->dom_family;
2944 kif->kf_sock_type = so->so_type;
2945 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2948 strlcpy(kif->kf_path, tty_devname(tp),
2949 sizeof(kif->kf_path));
2952 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
2953 if (ks != NULL && ksem_info != NULL)
2954 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
2955 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2959 FILEDESC_SUNLOCK(fdp);
2965 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2966 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2967 #endif /* COMPAT_FREEBSD7 */
2969 #ifdef KINFO_FILE_SIZE
2970 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2974 export_vnode_for_sysctl(struct vnode *vp, int type,
2975 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2978 char *fullpath, *freepath;
2981 bzero(kif, sizeof(*kif));
2985 kif->kf_type = KF_TYPE_VNODE;
2986 /* This function only handles directories. */
2987 if (vp->v_type != VDIR) {
2991 kif->kf_vnode_type = KF_VTYPE_VDIR;
2994 * This is not a true file descriptor, so we set a bogus refcount
2995 * and offset to indicate these fields should be ignored.
2997 kif->kf_ref_count = -1;
2998 kif->kf_offset = -1;
3002 FILEDESC_SUNLOCK(fdp);
3003 vn_fullpath(curthread, vp, &fullpath, &freepath);
3004 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3006 VFS_UNLOCK_GIANT(vfslocked);
3007 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3008 if (freepath != NULL)
3009 free(freepath, M_TEMP);
3010 /* Pack record size down */
3011 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3012 strlen(kif->kf_path) + 1;
3013 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3014 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3015 FILEDESC_SLOCK(fdp);
3020 * Get per-process file descriptors for use by procstat(1), et al.
3023 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3025 char *fullpath, *freepath;
3026 struct kinfo_file *kif;
3027 struct filedesc *fdp;
3028 int error, i, *name;
3029 struct shmfd *shmfd;
3040 if ((p = pfind((pid_t)name[0])) == NULL)
3042 if ((error = p_candebug(curthread, p))) {
3050 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3051 FILEDESC_SLOCK(fdp);
3052 if (fdp->fd_cdir != NULL)
3053 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3055 if (fdp->fd_rdir != NULL)
3056 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3058 if (fdp->fd_jdir != NULL)
3059 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3061 for (i = 0; i < fdp->fd_nfiles; i++) {
3062 if ((fp = fdp->fd_ofiles[i]) == NULL)
3064 bzero(kif, sizeof(*kif));
3071 switch (fp->f_type) {
3073 kif->kf_type = KF_TYPE_VNODE;
3078 kif->kf_type = KF_TYPE_SOCKET;
3083 kif->kf_type = KF_TYPE_PIPE;
3087 kif->kf_type = KF_TYPE_FIFO;
3092 kif->kf_type = KF_TYPE_KQUEUE;
3096 kif->kf_type = KF_TYPE_CRYPTO;
3100 kif->kf_type = KF_TYPE_MQUEUE;
3104 kif->kf_type = KF_TYPE_SHM;
3109 kif->kf_type = KF_TYPE_SEM;
3114 kif->kf_type = KF_TYPE_PTS;
3119 kif->kf_type = KF_TYPE_UNKNOWN;
3122 kif->kf_ref_count = fp->f_count;
3123 if (fp->f_flag & FREAD)
3124 kif->kf_flags |= KF_FLAG_READ;
3125 if (fp->f_flag & FWRITE)
3126 kif->kf_flags |= KF_FLAG_WRITE;
3127 if (fp->f_flag & FAPPEND)
3128 kif->kf_flags |= KF_FLAG_APPEND;
3129 if (fp->f_flag & FASYNC)
3130 kif->kf_flags |= KF_FLAG_ASYNC;
3131 if (fp->f_flag & FFSYNC)
3132 kif->kf_flags |= KF_FLAG_FSYNC;
3133 if (fp->f_flag & FNONBLOCK)
3134 kif->kf_flags |= KF_FLAG_NONBLOCK;
3135 if (fp->f_flag & O_DIRECT)
3136 kif->kf_flags |= KF_FLAG_DIRECT;
3137 if (fp->f_flag & FHASLOCK)
3138 kif->kf_flags |= KF_FLAG_HASLOCK;
3139 kif->kf_offset = fp->f_offset;
3142 switch (vp->v_type) {
3144 kif->kf_vnode_type = KF_VTYPE_VNON;
3147 kif->kf_vnode_type = KF_VTYPE_VREG;
3150 kif->kf_vnode_type = KF_VTYPE_VDIR;
3153 kif->kf_vnode_type = KF_VTYPE_VBLK;
3156 kif->kf_vnode_type = KF_VTYPE_VCHR;
3159 kif->kf_vnode_type = KF_VTYPE_VLNK;
3162 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3165 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3168 kif->kf_vnode_type = KF_VTYPE_VBAD;
3171 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3175 * It is OK to drop the filedesc lock here as we will
3176 * re-validate and re-evaluate its properties when
3177 * the loop continues.
3181 FILEDESC_SUNLOCK(fdp);
3182 vn_fullpath(curthread, vp, &fullpath, &freepath);
3183 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3185 VFS_UNLOCK_GIANT(vfslocked);
3186 strlcpy(kif->kf_path, fullpath,
3187 sizeof(kif->kf_path));
3188 if (freepath != NULL)
3189 free(freepath, M_TEMP);
3190 FILEDESC_SLOCK(fdp);
3193 struct sockaddr *sa;
3195 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3196 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3197 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3200 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3201 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3202 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3205 kif->kf_sock_domain =
3206 so->so_proto->pr_domain->dom_family;
3207 kif->kf_sock_type = so->so_type;
3208 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3211 strlcpy(kif->kf_path, tty_devname(tp),
3212 sizeof(kif->kf_path));
3215 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3216 if (ks != NULL && ksem_info != NULL)
3217 ksem_info(ks, kif->kf_path, sizeof(kif->kf_path), NULL);
3218 /* Pack record size down */
3219 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3220 strlen(kif->kf_path) + 1;
3221 kif->kf_structsize = roundup(kif->kf_structsize,
3223 oldidx = req->oldidx;
3224 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3226 if (error == ENOMEM) {
3228 * The hack to keep the ABI of sysctl
3229 * kern.proc.filedesc intact, but not
3230 * to account a partially copied
3231 * kinfo_file into the oldidx.
3233 req->oldidx = oldidx;
3239 FILEDESC_SUNLOCK(fdp);
3245 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3246 sysctl_kern_proc_filedesc, "Process filedesc entries");
3250 * For the purposes of debugging, generate a human-readable string for the
3254 file_type_to_name(short type)
3284 * For the purposes of debugging, identify a process (if any, perhaps one of
3285 * many) that references the passed file in its file descriptor array. Return
3288 static struct proc *
3289 file_to_first_proc(struct file *fp)
3291 struct filedesc *fdp;
3295 FOREACH_PROC_IN_SYSTEM(p) {
3296 if (p->p_state == PRS_NEW)
3301 for (n = 0; n < fdp->fd_nfiles; n++) {
3302 if (fp == fdp->fd_ofiles[n])
3310 db_print_file(struct file *fp, int header)
3315 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3316 "File", "Type", "Data", "Flag", "GCFl", "Count",
3317 "MCount", "Vnode", "FPID", "FCmd");
3318 p = file_to_first_proc(fp);
3319 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3320 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3321 0, fp->f_count, 0, fp->f_vnode,
3322 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3325 DB_SHOW_COMMAND(file, db_show_file)
3330 db_printf("usage: show file <addr>\n");
3333 fp = (struct file *)addr;
3334 db_print_file(fp, 1);
3337 DB_SHOW_COMMAND(files, db_show_files)
3339 struct filedesc *fdp;
3346 FOREACH_PROC_IN_SYSTEM(p) {
3347 if (p->p_state == PRS_NEW)
3349 if ((fdp = p->p_fd) == NULL)
3351 for (n = 0; n < fdp->fd_nfiles; ++n) {
3352 if ((fp = fdp->fd_ofiles[n]) == NULL)
3354 db_print_file(fp, header);
3361 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3362 &maxfilesperproc, 0, "Maximum files allowed open per process");
3364 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3365 &maxfiles, 0, "Maximum number of files");
3367 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3368 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3372 filelistinit(void *dummy)
3375 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3376 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3377 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3378 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3380 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3382 /*-------------------------------------------------------------------*/
3385 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3392 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3399 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3406 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3413 badfo_kqfilter(struct file *fp, struct knote *kn)
3420 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3427 badfo_close(struct file *fp, struct thread *td)
3433 struct fileops badfileops = {
3434 .fo_read = badfo_readwrite,
3435 .fo_write = badfo_readwrite,
3436 .fo_truncate = badfo_truncate,
3437 .fo_ioctl = badfo_ioctl,
3438 .fo_poll = badfo_poll,
3439 .fo_kqfilter = badfo_kqfilter,
3440 .fo_stat = badfo_stat,
3441 .fo_close = badfo_close,
3445 /*-------------------------------------------------------------------*/
3448 * File Descriptor pseudo-device driver (/dev/fd/).
3450 * Opening minor device N dup()s the file (if any) connected to file
3451 * descriptor N belonging to the calling process. Note that this driver
3452 * consists of only the ``open()'' routine, because all subsequent
3453 * references to this file will be direct to the other driver.
3455 * XXX: we could give this one a cloning event handler if necessary.
3460 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3464 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3465 * the file descriptor being sought for duplication. The error
3466 * return ensures that the vnode for this device will be released
3467 * by vn_open. Open will detect this special error and take the
3468 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3469 * will simply report the error.
3471 td->td_dupfd = dev2unit(dev);
3475 static struct cdevsw fildesc_cdevsw = {
3476 .d_version = D_VERSION,
3482 fildesc_drvinit(void *unused)
3486 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3487 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3488 make_dev_alias(dev, "stdin");
3489 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3490 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3491 make_dev_alias(dev, "stdout");
3492 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3493 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3494 make_dev_alias(dev, "stderr");
3497 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);