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>
55 #include <sys/limits.h>
57 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mqueue.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
65 #include <sys/protosw.h>
66 #include <sys/resourcevar.h>
67 #include <sys/signalvar.h>
68 #include <sys/socketvar.h>
71 #include <sys/syscallsubr.h>
72 #include <sys/sysctl.h>
73 #include <sys/sysproto.h>
75 #include <sys/unistd.h>
77 #include <sys/vnode.h>
79 #include <sys/ktrace.h>
84 #include <security/audit/audit.h>
90 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
91 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
92 "file desc to leader structures");
93 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
95 MALLOC_DECLARE(M_FADVISE);
97 static uma_zone_t file_zone;
100 /* Flags for do_dup() */
101 #define DUP_FIXED 0x1 /* Force fixed allocation */
102 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
103 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
105 static int do_dup(struct thread *td, int flags, int old, int new,
107 static int fd_first_free(struct filedesc *, int, int);
108 static int fd_last_used(struct filedesc *, int, int);
109 static void fdgrowtable(struct filedesc *, int);
110 static void fdunused(struct filedesc *fdp, int fd);
111 static void fdused(struct filedesc *fdp, int fd);
114 * A process is initially started out with NDFILE descriptors stored within
115 * this structure, selected to be enough for typical applications based on
116 * the historical limit of 20 open files (and the usage of descriptors by
117 * shells). If these descriptors are exhausted, a larger descriptor table
118 * may be allocated, up to a process' resource limit; the internal arrays
122 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
123 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
124 #define NDSLOT(x) ((x) / NDENTRIES)
125 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
126 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
129 * Storage required per open file descriptor.
131 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
134 * Storage to hold unused ofiles that need to be reclaimed.
137 struct file **ft_table;
138 SLIST_ENTRY(freetable) ft_next;
142 * Basic allocation of descriptors:
143 * one of the above, plus arrays for NDFILE descriptors.
146 struct filedesc fd_fd;
148 * ofiles which need to be reclaimed on free.
150 SLIST_HEAD(,freetable) fd_free;
152 * These arrays are used when the number of open files is
153 * <= NDFILE, and are then pointed to by the pointers above.
155 struct file *fd_dfiles[NDFILE];
156 char fd_dfileflags[NDFILE];
157 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
161 * Descriptor management.
163 volatile int openfiles; /* actual number of open files */
164 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
165 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
167 /* A mutex to protect the association between a proc and filedesc. */
168 static struct mtx fdesc_mtx;
171 * Find the first zero bit in the given bitmap, starting at low and not
172 * exceeding size - 1.
175 fd_first_free(struct filedesc *fdp, int low, int size)
177 NDSLOTTYPE *map = fdp->fd_map;
185 if (low % NDENTRIES) {
186 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
187 if ((mask &= ~map[off]) != 0UL)
188 return (off * NDENTRIES + ffsl(mask) - 1);
191 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
192 if (map[off] != ~0UL)
193 return (off * NDENTRIES + ffsl(~map[off]) - 1);
198 * Find the highest non-zero bit in the given bitmap, starting at low and
199 * not exceeding size - 1.
202 fd_last_used(struct filedesc *fdp, int low, int size)
204 NDSLOTTYPE *map = fdp->fd_map;
212 if (size % NDENTRIES) {
213 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
214 if ((mask &= map[off]) != 0)
215 return (off * NDENTRIES + flsl(mask) - 1);
218 for (minoff = NDSLOT(low); off >= minoff; --off)
220 return (off * NDENTRIES + flsl(map[off]) - 1);
225 fdisused(struct filedesc *fdp, int fd)
227 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
228 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
229 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
233 * Mark a file descriptor as used.
236 fdused(struct filedesc *fdp, int fd)
239 FILEDESC_XLOCK_ASSERT(fdp);
240 KASSERT(!fdisused(fdp, fd),
241 ("fd already used"));
243 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
244 if (fd > fdp->fd_lastfile)
245 fdp->fd_lastfile = fd;
246 if (fd == fdp->fd_freefile)
247 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
251 * Mark a file descriptor as unused.
254 fdunused(struct filedesc *fdp, int fd)
257 FILEDESC_XLOCK_ASSERT(fdp);
258 KASSERT(fdisused(fdp, fd),
259 ("fd is already unused"));
260 KASSERT(fdp->fd_ofiles[fd] == NULL,
261 ("fd is still in use"));
263 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
264 if (fd < fdp->fd_freefile)
265 fdp->fd_freefile = fd;
266 if (fd == fdp->fd_lastfile)
267 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
271 * System calls on descriptors.
273 #ifndef _SYS_SYSPROTO_H_
274 struct getdtablesize_args {
280 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
282 struct proc *p = td->td_proc;
286 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
292 * Duplicate a file descriptor to a particular value.
294 * Note: keep in mind that a potential race condition exists when closing
295 * descriptors from a shared descriptor table (via rfork).
297 #ifndef _SYS_SYSPROTO_H_
305 dup2(struct thread *td, struct dup2_args *uap)
308 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
313 * Duplicate a file descriptor.
315 #ifndef _SYS_SYSPROTO_H_
322 dup(struct thread *td, struct dup_args *uap)
325 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
329 * The file control system call.
331 #ifndef _SYS_SYSPROTO_H_
340 fcntl(struct thread *td, struct fcntl_args *uap)
355 * Convert old flock structure to new.
357 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
358 fl.l_start = ofl.l_start;
359 fl.l_len = ofl.l_len;
360 fl.l_pid = ofl.l_pid;
361 fl.l_type = ofl.l_type;
362 fl.l_whence = ofl.l_whence;
382 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
391 error = kern_fcntl(td, uap->fd, cmd, arg);
394 if (uap->cmd == F_OGETLK) {
395 ofl.l_start = fl.l_start;
396 ofl.l_len = fl.l_len;
397 ofl.l_pid = fl.l_pid;
398 ofl.l_type = fl.l_type;
399 ofl.l_whence = fl.l_whence;
400 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
401 } else if (uap->cmd == F_GETLK) {
402 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
407 static inline struct file *
408 fdtofp(int fd, struct filedesc *fdp)
412 FILEDESC_LOCK_ASSERT(fdp);
413 if ((unsigned)fd >= fdp->fd_nfiles ||
414 (fp = fdp->fd_ofiles[fd]) == NULL)
420 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
422 struct filedesc *fdp;
442 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
445 case F_DUPFD_CLOEXEC:
447 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp,
453 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
456 case F_DUP2FD_CLOEXEC:
458 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp,
464 if ((fp = fdtofp(fd, fdp)) == NULL) {
465 FILEDESC_SUNLOCK(fdp);
469 pop = &fdp->fd_ofileflags[fd];
470 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
471 FILEDESC_SUNLOCK(fdp);
476 if ((fp = fdtofp(fd, fdp)) == NULL) {
477 FILEDESC_XUNLOCK(fdp);
481 pop = &fdp->fd_ofileflags[fd];
482 *pop = (*pop &~ UF_EXCLOSE) |
483 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
484 FILEDESC_XUNLOCK(fdp);
489 if ((fp = fdtofp(fd, fdp)) == NULL) {
490 FILEDESC_SUNLOCK(fdp);
494 td->td_retval[0] = OFLAGS(fp->f_flag);
495 FILEDESC_SUNLOCK(fdp);
500 if ((fp = fdtofp(fd, fdp)) == NULL) {
501 FILEDESC_SUNLOCK(fdp);
506 FILEDESC_SUNLOCK(fdp);
508 tmp = flg = fp->f_flag;
510 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
511 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
512 tmp = fp->f_flag & FNONBLOCK;
513 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
518 tmp = fp->f_flag & FASYNC;
519 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
524 atomic_clear_int(&fp->f_flag, FNONBLOCK);
526 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
532 if ((fp = fdtofp(fd, fdp)) == NULL) {
533 FILEDESC_SUNLOCK(fdp);
538 FILEDESC_SUNLOCK(fdp);
539 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
541 td->td_retval[0] = tmp;
547 if ((fp = fdtofp(fd, fdp)) == NULL) {
548 FILEDESC_SUNLOCK(fdp);
553 FILEDESC_SUNLOCK(fdp);
555 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
560 error = priv_check(td, PRIV_NFS_LOCKD);
568 /* FALLTHROUGH F_SETLK */
573 if ((fp = fdtofp(fd, fdp)) == NULL) {
574 FILEDESC_SUNLOCK(fdp);
578 if (fp->f_type != DTYPE_VNODE) {
579 FILEDESC_SUNLOCK(fdp);
583 flp = (struct flock *)arg;
584 if (flp->l_whence == SEEK_CUR) {
585 if (fp->f_offset < 0 ||
587 fp->f_offset > OFF_MAX - flp->l_start)) {
588 FILEDESC_SUNLOCK(fdp);
592 flp->l_start += fp->f_offset;
596 * VOP_ADVLOCK() may block.
599 FILEDESC_SUNLOCK(fdp);
601 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
602 switch (flp->l_type) {
604 if ((fp->f_flag & FREAD) == 0) {
608 PROC_LOCK(p->p_leader);
609 p->p_leader->p_flag |= P_ADVLOCK;
610 PROC_UNLOCK(p->p_leader);
611 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
615 if ((fp->f_flag & FWRITE) == 0) {
619 PROC_LOCK(p->p_leader);
620 p->p_leader->p_flag |= P_ADVLOCK;
621 PROC_UNLOCK(p->p_leader);
622 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
626 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
631 * Temporary api for testing remote lock
634 if (flg != F_REMOTE) {
638 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
639 F_UNLCKSYS, flp, flg);
645 VFS_UNLOCK_GIANT(vfslocked);
647 /* Check for race with close */
649 if ((unsigned) fd >= fdp->fd_nfiles ||
650 fp != fdp->fd_ofiles[fd]) {
651 FILEDESC_SUNLOCK(fdp);
652 flp->l_whence = SEEK_SET;
655 flp->l_type = F_UNLCK;
656 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
657 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
658 F_UNLCK, flp, F_POSIX);
659 VFS_UNLOCK_GIANT(vfslocked);
662 FILEDESC_SUNLOCK(fdp);
668 if ((fp = fdtofp(fd, fdp)) == NULL) {
669 FILEDESC_SUNLOCK(fdp);
673 if (fp->f_type != DTYPE_VNODE) {
674 FILEDESC_SUNLOCK(fdp);
678 flp = (struct flock *)arg;
679 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
680 flp->l_type != F_UNLCK) {
681 FILEDESC_SUNLOCK(fdp);
685 if (flp->l_whence == SEEK_CUR) {
686 if ((flp->l_start > 0 &&
687 fp->f_offset > OFF_MAX - flp->l_start) ||
689 fp->f_offset < OFF_MIN - flp->l_start)) {
690 FILEDESC_SUNLOCK(fdp);
694 flp->l_start += fp->f_offset;
697 * VOP_ADVLOCK() may block.
700 FILEDESC_SUNLOCK(fdp);
702 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
703 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
705 VFS_UNLOCK_GIANT(vfslocked);
711 arg = arg ? 128 * 1024: 0;
715 if ((fp = fdtofp(fd, fdp)) == NULL) {
716 FILEDESC_SUNLOCK(fdp);
720 if (fp->f_type != DTYPE_VNODE) {
721 FILEDESC_SUNLOCK(fdp);
726 FILEDESC_SUNLOCK(fdp);
729 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
730 error = vn_lock(vp, LK_SHARED);
732 goto readahead_vnlock_fail;
733 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
735 fp->f_seqcount = (arg + bsize - 1) / bsize;
737 new = old = fp->f_flag;
739 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
740 readahead_vnlock_fail:
741 VFS_UNLOCK_GIANT(vfslocked);
745 new = old = fp->f_flag;
747 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
756 VFS_UNLOCK_GIANT(vfslocked);
761 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
764 do_dup(struct thread *td, int flags, int old, int new,
767 struct filedesc *fdp;
771 int error, holdleaders, maxfd;
777 * Verify we have a valid descriptor to dup from and possibly to
778 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
779 * return EINVAL when the new descriptor is out of bounds.
784 return (flags & DUP_FCNTL ? EINVAL : EBADF);
786 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
789 return (flags & DUP_FCNTL ? EINVAL : EBADF);
792 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
793 FILEDESC_XUNLOCK(fdp);
796 if (flags & DUP_FIXED && old == new) {
798 if (flags & DUP_CLOEXEC)
799 fdp->fd_ofileflags[new] |= UF_EXCLOSE;
800 FILEDESC_XUNLOCK(fdp);
803 fp = fdp->fd_ofiles[old];
807 * If the caller specified a file descriptor, make sure the file
808 * table is large enough to hold it, and grab it. Otherwise, just
809 * allocate a new descriptor the usual way. Since the filedesc
810 * lock may be temporarily dropped in the process, we have to look
813 if (flags & DUP_FIXED) {
814 if (new >= fdp->fd_nfiles)
815 fdgrowtable(fdp, new + 1);
816 if (fdp->fd_ofiles[new] == NULL)
819 if ((error = fdalloc(td, new, &new)) != 0) {
820 FILEDESC_XUNLOCK(fdp);
827 * If the old file changed out from under us then treat it as a
828 * bad file descriptor. Userland should do its own locking to
831 if (fdp->fd_ofiles[old] != fp) {
832 /* we've allocated a descriptor which we won't use */
833 if (fdp->fd_ofiles[new] == NULL)
835 FILEDESC_XUNLOCK(fdp);
840 ("new fd is same as old"));
843 * Save info on the descriptor being overwritten. We cannot close
844 * it without introducing an ownership race for the slot, since we
845 * need to drop the filedesc lock to call closef().
847 * XXX this duplicates parts of close().
849 delfp = fdp->fd_ofiles[new];
852 if (td->td_proc->p_fdtol != NULL) {
854 * Ask fdfree() to sleep to ensure that all relevant
855 * process leaders can be traversed in closef().
857 fdp->fd_holdleaderscount++;
863 * Duplicate the source descriptor
865 fdp->fd_ofiles[new] = fp;
866 if ((flags & DUP_CLOEXEC) != 0)
867 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] | UF_EXCLOSE;
869 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] & ~UF_EXCLOSE;
870 if (new > fdp->fd_lastfile)
871 fdp->fd_lastfile = new;
875 * If we dup'd over a valid file, we now own the reference to it
876 * and must dispose of it using closef() semantics (as if a
877 * close() were performed on it).
879 * XXX this duplicates parts of close().
882 knote_fdclose(td, new);
883 if (delfp->f_type == DTYPE_MQUEUE)
884 mq_fdclose(td, new, delfp);
885 FILEDESC_XUNLOCK(fdp);
886 (void) closef(delfp, td);
889 fdp->fd_holdleaderscount--;
890 if (fdp->fd_holdleaderscount == 0 &&
891 fdp->fd_holdleaderswakeup != 0) {
892 fdp->fd_holdleaderswakeup = 0;
893 wakeup(&fdp->fd_holdleaderscount);
895 FILEDESC_XUNLOCK(fdp);
898 FILEDESC_XUNLOCK(fdp);
904 * If sigio is on the list associated with a process or process group,
905 * disable signalling from the device, remove sigio from the list and
909 funsetown(struct sigio **sigiop)
919 *(sigio->sio_myref) = NULL;
920 if ((sigio)->sio_pgid < 0) {
921 struct pgrp *pg = (sigio)->sio_pgrp;
923 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
927 struct proc *p = (sigio)->sio_proc;
929 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
934 crfree(sigio->sio_ucred);
935 free(sigio, M_SIGIO);
939 * Free a list of sigio structures.
940 * We only need to lock the SIGIO_LOCK because we have made ourselves
941 * inaccessible to callers of fsetown and therefore do not need to lock
942 * the proc or pgrp struct for the list manipulation.
945 funsetownlst(struct sigiolst *sigiolst)
951 sigio = SLIST_FIRST(sigiolst);
958 * Every entry of the list should belong
959 * to a single proc or pgrp.
961 if (sigio->sio_pgid < 0) {
962 pg = sigio->sio_pgrp;
963 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
964 } else /* if (sigio->sio_pgid > 0) */ {
966 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
970 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
971 *(sigio->sio_myref) = NULL;
973 KASSERT(sigio->sio_pgid < 0,
974 ("Proc sigio in pgrp sigio list"));
975 KASSERT(sigio->sio_pgrp == pg,
976 ("Bogus pgrp in sigio list"));
978 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
981 } else /* if (p != NULL) */ {
982 KASSERT(sigio->sio_pgid > 0,
983 ("Pgrp sigio in proc sigio list"));
984 KASSERT(sigio->sio_proc == p,
985 ("Bogus proc in sigio list"));
987 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
992 crfree(sigio->sio_ucred);
993 free(sigio, M_SIGIO);
1000 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1002 * After permission checking, add a sigio structure to the sigio list for
1003 * the process or process group.
1006 fsetown(pid_t pgid, struct sigio **sigiop)
1010 struct sigio *sigio;
1020 /* Allocate and fill in the new sigio out of locks. */
1021 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1022 sigio->sio_pgid = pgid;
1023 sigio->sio_ucred = crhold(curthread->td_ucred);
1024 sigio->sio_myref = sigiop;
1026 sx_slock(&proctree_lock);
1035 * Policy - Don't allow a process to FSETOWN a process
1036 * in another session.
1038 * Remove this test to allow maximum flexibility or
1039 * restrict FSETOWN to the current process or process
1040 * group for maximum safety.
1043 if (proc->p_session != curthread->td_proc->p_session) {
1049 } else /* if (pgid < 0) */ {
1050 pgrp = pgfind(-pgid);
1058 * Policy - Don't allow a process to FSETOWN a process
1059 * in another session.
1061 * Remove this test to allow maximum flexibility or
1062 * restrict FSETOWN to the current process or process
1063 * group for maximum safety.
1065 if (pgrp->pg_session != curthread->td_proc->p_session) {
1076 * Since funsetownlst() is called without the proctree
1077 * locked, we need to check for P_WEXIT.
1078 * XXX: is ESRCH correct?
1080 if ((proc->p_flag & P_WEXIT) != 0) {
1085 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1086 sigio->sio_proc = proc;
1090 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1091 sigio->sio_pgrp = pgrp;
1094 sx_sunlock(&proctree_lock);
1101 sx_sunlock(&proctree_lock);
1102 crfree(sigio->sio_ucred);
1103 free(sigio, M_SIGIO);
1108 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1112 struct sigio **sigiop;
1117 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1123 * Close a file descriptor.
1125 #ifndef _SYS_SYSPROTO_H_
1134 struct close_args *uap;
1137 return (kern_close(td, uap->fd));
1145 struct filedesc *fdp;
1152 fdp = td->td_proc->p_fd;
1154 AUDIT_SYSCLOSE(td, fd);
1156 FILEDESC_XLOCK(fdp);
1157 if ((unsigned)fd >= fdp->fd_nfiles ||
1158 (fp = fdp->fd_ofiles[fd]) == NULL) {
1159 FILEDESC_XUNLOCK(fdp);
1162 fdp->fd_ofiles[fd] = NULL;
1163 fdp->fd_ofileflags[fd] = 0;
1165 if (td->td_proc->p_fdtol != NULL) {
1167 * Ask fdfree() to sleep to ensure that all relevant
1168 * process leaders can be traversed in closef().
1170 fdp->fd_holdleaderscount++;
1175 * We now hold the fp reference that used to be owned by the
1176 * descriptor array. We have to unlock the FILEDESC *AFTER*
1177 * knote_fdclose to prevent a race of the fd getting opened, a knote
1178 * added, and deleteing a knote for the new fd.
1180 knote_fdclose(td, fd);
1181 if (fp->f_type == DTYPE_MQUEUE)
1182 mq_fdclose(td, fd, fp);
1183 FILEDESC_XUNLOCK(fdp);
1185 error = closef(fp, td);
1187 FILEDESC_XLOCK(fdp);
1188 fdp->fd_holdleaderscount--;
1189 if (fdp->fd_holdleaderscount == 0 &&
1190 fdp->fd_holdleaderswakeup != 0) {
1191 fdp->fd_holdleaderswakeup = 0;
1192 wakeup(&fdp->fd_holdleaderscount);
1194 FILEDESC_XUNLOCK(fdp);
1200 * Close open file descriptors.
1202 #ifndef _SYS_SYSPROTO_H_
1203 struct closefrom_args {
1209 closefrom(struct thread *td, struct closefrom_args *uap)
1211 struct filedesc *fdp;
1214 fdp = td->td_proc->p_fd;
1215 AUDIT_ARG_FD(uap->lowfd);
1218 * Treat negative starting file descriptor values identical to
1219 * closefrom(0) which closes all files.
1223 FILEDESC_SLOCK(fdp);
1224 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1225 if (fdp->fd_ofiles[fd] != NULL) {
1226 FILEDESC_SUNLOCK(fdp);
1227 (void)kern_close(td, fd);
1228 FILEDESC_SLOCK(fdp);
1231 FILEDESC_SUNLOCK(fdp);
1235 #if defined(COMPAT_43)
1237 * Return status information about a file descriptor.
1239 #ifndef _SYS_SYSPROTO_H_
1240 struct ofstat_args {
1247 ofstat(struct thread *td, struct ofstat_args *uap)
1253 error = kern_fstat(td, uap->fd, &ub);
1256 error = copyout(&oub, uap->sb, sizeof(oub));
1260 #endif /* COMPAT_43 */
1263 * Return status information about a file descriptor.
1265 #ifndef _SYS_SYSPROTO_H_
1273 fstat(struct thread *td, struct fstat_args *uap)
1278 error = kern_fstat(td, uap->fd, &ub);
1280 error = copyout(&ub, uap->sb, sizeof(ub));
1285 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1292 if ((error = fget(td, fd, &fp)) != 0)
1295 AUDIT_ARG_FILE(td->td_proc, fp);
1297 error = fo_stat(fp, sbp, td->td_ucred, td);
1300 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1307 * Return status information about a file descriptor.
1309 #ifndef _SYS_SYSPROTO_H_
1310 struct nfstat_args {
1317 nfstat(struct thread *td, struct nfstat_args *uap)
1323 error = kern_fstat(td, uap->fd, &ub);
1325 cvtnstat(&ub, &nub);
1326 error = copyout(&nub, uap->sb, sizeof(nub));
1332 * Return pathconf information about a file descriptor.
1334 #ifndef _SYS_SYSPROTO_H_
1335 struct fpathconf_args {
1342 fpathconf(struct thread *td, struct fpathconf_args *uap)
1348 if ((error = fget(td, uap->fd, &fp)) != 0)
1351 /* If asynchronous I/O is available, it works for all descriptors. */
1352 if (uap->name == _PC_ASYNC_IO) {
1353 td->td_retval[0] = async_io_version;
1359 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1360 vn_lock(vp, LK_SHARED | LK_RETRY);
1361 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1363 VFS_UNLOCK_GIANT(vfslocked);
1364 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1365 if (uap->name != _PC_PIPE_BUF) {
1368 td->td_retval[0] = PIPE_BUF;
1380 * Grow the file table to accomodate (at least) nfd descriptors. This may
1381 * block and drop the filedesc lock, but it will reacquire it before
1385 fdgrowtable(struct filedesc *fdp, int nfd)
1387 struct filedesc0 *fdp0;
1388 struct freetable *fo;
1389 struct file **ntable;
1390 struct file **otable;
1392 int nnfiles, onfiles;
1395 FILEDESC_XLOCK_ASSERT(fdp);
1397 KASSERT(fdp->fd_nfiles > 0,
1398 ("zero-length file table"));
1400 /* compute the size of the new table */
1401 onfiles = fdp->fd_nfiles;
1402 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1403 if (nnfiles <= onfiles)
1404 /* the table is already large enough */
1407 /* allocate a new table and (if required) new bitmaps */
1408 FILEDESC_XUNLOCK(fdp);
1409 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1410 M_FILEDESC, M_ZERO | M_WAITOK);
1411 nfileflags = (char *)&ntable[nnfiles];
1412 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1413 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1414 M_FILEDESC, M_ZERO | M_WAITOK);
1417 FILEDESC_XLOCK(fdp);
1420 * We now have new tables ready to go. Since we dropped the
1421 * filedesc lock to call malloc(), watch out for a race.
1423 onfiles = fdp->fd_nfiles;
1424 if (onfiles >= nnfiles) {
1425 /* we lost the race, but that's OK */
1426 free(ntable, M_FILEDESC);
1428 free(nmap, M_FILEDESC);
1431 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1432 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1433 otable = fdp->fd_ofiles;
1434 fdp->fd_ofileflags = nfileflags;
1435 fdp->fd_ofiles = ntable;
1437 * We must preserve ofiles until the process exits because we can't
1438 * be certain that no threads have references to the old table via
1441 if (onfiles > NDFILE) {
1442 fo = (struct freetable *)&otable[onfiles];
1443 fdp0 = (struct filedesc0 *)fdp;
1444 fo->ft_table = otable;
1445 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1447 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1448 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1449 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1450 free(fdp->fd_map, M_FILEDESC);
1453 fdp->fd_nfiles = nnfiles;
1457 * Allocate a file descriptor for the process.
1460 fdalloc(struct thread *td, int minfd, int *result)
1462 struct proc *p = td->td_proc;
1463 struct filedesc *fdp = p->p_fd;
1466 FILEDESC_XLOCK_ASSERT(fdp);
1468 if (fdp->fd_freefile > minfd)
1469 minfd = fdp->fd_freefile;
1472 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1476 * Search the bitmap for a free descriptor. If none is found, try
1477 * to grow the file table. Keep at it until we either get a file
1478 * descriptor or run into process or system limits; fdgrowtable()
1479 * may drop the filedesc lock, so we're in a race.
1482 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1485 if (fd < fdp->fd_nfiles)
1487 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1491 * Perform some sanity checks, then mark the file descriptor as
1492 * used and return it to the caller.
1494 KASSERT(!fdisused(fdp, fd),
1495 ("fd_first_free() returned non-free descriptor"));
1496 KASSERT(fdp->fd_ofiles[fd] == NULL,
1497 ("free descriptor isn't"));
1498 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1505 * Check to see whether n user file descriptors are available to the process
1509 fdavail(struct thread *td, int n)
1511 struct proc *p = td->td_proc;
1512 struct filedesc *fdp = td->td_proc->p_fd;
1516 FILEDESC_LOCK_ASSERT(fdp);
1519 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1521 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1523 last = min(fdp->fd_nfiles, lim);
1524 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1525 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1526 if (*fpp == NULL && --n <= 0)
1533 * Create a new open file structure and allocate a file decriptor for the
1534 * process that refers to it. We add one reference to the file for the
1535 * descriptor table and one reference for resultfp. This is to prevent us
1536 * being preempted and the entry in the descriptor table closed after we
1537 * release the FILEDESC lock.
1540 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1542 struct proc *p = td->td_proc;
1545 int maxuserfiles = maxfiles - (maxfiles / 20);
1546 static struct timeval lastfail;
1549 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1550 if ((openfiles >= maxuserfiles &&
1551 priv_check(td, PRIV_MAXFILES) != 0) ||
1552 openfiles >= maxfiles) {
1553 if (ppsratecheck(&lastfail, &curfail, 1)) {
1554 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1555 td->td_ucred->cr_ruid);
1557 uma_zfree(file_zone, fp);
1560 atomic_add_int(&openfiles, 1);
1563 * If the process has file descriptor zero open, add the new file
1564 * descriptor to the list of open files at that point, otherwise
1565 * put it at the front of the list of open files.
1567 refcount_init(&fp->f_count, 1);
1570 fp->f_cred = crhold(td->td_ucred);
1571 fp->f_ops = &badfileops;
1574 FILEDESC_XLOCK(p->p_fd);
1575 if ((error = fdalloc(td, 0, &i))) {
1576 FILEDESC_XUNLOCK(p->p_fd);
1582 p->p_fd->fd_ofiles[i] = fp;
1583 if ((flags & O_CLOEXEC) != 0)
1584 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1585 FILEDESC_XUNLOCK(p->p_fd);
1594 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1597 return (fallocf(td, resultfp, resultfd, 0));
1601 * Build a new filedesc structure from another.
1602 * Copy the current, root, and jail root vnode references.
1605 fdinit(struct filedesc *fdp)
1607 struct filedesc0 *newfdp;
1609 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1610 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1612 FILEDESC_XLOCK(fdp);
1613 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1614 if (newfdp->fd_fd.fd_cdir)
1615 VREF(newfdp->fd_fd.fd_cdir);
1616 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1617 if (newfdp->fd_fd.fd_rdir)
1618 VREF(newfdp->fd_fd.fd_rdir);
1619 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1620 if (newfdp->fd_fd.fd_jdir)
1621 VREF(newfdp->fd_fd.fd_jdir);
1622 FILEDESC_XUNLOCK(fdp);
1625 /* Create the file descriptor table. */
1626 newfdp->fd_fd.fd_refcnt = 1;
1627 newfdp->fd_fd.fd_holdcnt = 1;
1628 newfdp->fd_fd.fd_cmask = CMASK;
1629 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1630 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1631 newfdp->fd_fd.fd_nfiles = NDFILE;
1632 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1633 newfdp->fd_fd.fd_lastfile = -1;
1634 return (&newfdp->fd_fd);
1637 static struct filedesc *
1638 fdhold(struct proc *p)
1640 struct filedesc *fdp;
1642 mtx_lock(&fdesc_mtx);
1646 mtx_unlock(&fdesc_mtx);
1651 fddrop(struct filedesc *fdp)
1653 struct filedesc0 *fdp0;
1654 struct freetable *ft;
1657 mtx_lock(&fdesc_mtx);
1658 i = --fdp->fd_holdcnt;
1659 mtx_unlock(&fdesc_mtx);
1663 FILEDESC_LOCK_DESTROY(fdp);
1664 fdp0 = (struct filedesc0 *)fdp;
1665 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1666 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1667 free(ft->ft_table, M_FILEDESC);
1669 free(fdp, M_FILEDESC);
1673 * Share a filedesc structure.
1676 fdshare(struct filedesc *fdp)
1679 FILEDESC_XLOCK(fdp);
1681 FILEDESC_XUNLOCK(fdp);
1686 * Unshare a filedesc structure, if necessary by making a copy
1689 fdunshare(struct proc *p, struct thread *td)
1692 FILEDESC_XLOCK(p->p_fd);
1693 if (p->p_fd->fd_refcnt > 1) {
1694 struct filedesc *tmp;
1696 FILEDESC_XUNLOCK(p->p_fd);
1697 tmp = fdcopy(p->p_fd);
1701 FILEDESC_XUNLOCK(p->p_fd);
1705 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1706 * this is to ease callers, not catch errors.
1709 fdcopy(struct filedesc *fdp)
1711 struct filedesc *newfdp;
1714 /* Certain daemons might not have file descriptors. */
1718 newfdp = fdinit(fdp);
1719 FILEDESC_SLOCK(fdp);
1720 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1721 FILEDESC_SUNLOCK(fdp);
1722 FILEDESC_XLOCK(newfdp);
1723 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1724 FILEDESC_XUNLOCK(newfdp);
1725 FILEDESC_SLOCK(fdp);
1727 /* copy everything except kqueue descriptors */
1728 newfdp->fd_freefile = -1;
1729 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1730 if (fdisused(fdp, i) &&
1731 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1732 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1733 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1734 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1735 fhold(newfdp->fd_ofiles[i]);
1736 newfdp->fd_lastfile = i;
1738 if (newfdp->fd_freefile == -1)
1739 newfdp->fd_freefile = i;
1742 newfdp->fd_cmask = fdp->fd_cmask;
1743 FILEDESC_SUNLOCK(fdp);
1744 FILEDESC_XLOCK(newfdp);
1745 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1746 if (newfdp->fd_ofiles[i] != NULL)
1748 if (newfdp->fd_freefile == -1)
1749 newfdp->fd_freefile = i;
1750 FILEDESC_XUNLOCK(newfdp);
1755 * Release a filedesc structure.
1758 fdfree(struct thread *td)
1760 struct filedesc *fdp;
1763 struct filedesc_to_leader *fdtol;
1765 struct vnode *cdir, *jdir, *rdir, *vp;
1768 /* Certain daemons might not have file descriptors. */
1769 fdp = td->td_proc->p_fd;
1773 /* Check for special need to clear POSIX style locks */
1774 fdtol = td->td_proc->p_fdtol;
1775 if (fdtol != NULL) {
1776 FILEDESC_XLOCK(fdp);
1777 KASSERT(fdtol->fdl_refcount > 0,
1778 ("filedesc_to_refcount botch: fdl_refcount=%d",
1779 fdtol->fdl_refcount));
1780 if (fdtol->fdl_refcount == 1 &&
1781 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1782 for (i = 0, fpp = fdp->fd_ofiles;
1783 i <= fdp->fd_lastfile;
1786 (*fpp)->f_type != DTYPE_VNODE)
1790 FILEDESC_XUNLOCK(fdp);
1791 lf.l_whence = SEEK_SET;
1794 lf.l_type = F_UNLCK;
1796 locked = VFS_LOCK_GIANT(vp->v_mount);
1797 (void) VOP_ADVLOCK(vp,
1798 (caddr_t)td->td_proc->
1803 VFS_UNLOCK_GIANT(locked);
1804 FILEDESC_XLOCK(fdp);
1806 fpp = fdp->fd_ofiles + i;
1810 if (fdtol->fdl_refcount == 1) {
1811 if (fdp->fd_holdleaderscount > 0 &&
1812 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1814 * close() or do_dup() has cleared a reference
1815 * in a shared file descriptor table.
1817 fdp->fd_holdleaderswakeup = 1;
1818 sx_sleep(&fdp->fd_holdleaderscount,
1819 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1822 if (fdtol->fdl_holdcount > 0) {
1824 * Ensure that fdtol->fdl_leader remains
1825 * valid in closef().
1827 fdtol->fdl_wakeup = 1;
1828 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1833 fdtol->fdl_refcount--;
1834 if (fdtol->fdl_refcount == 0 &&
1835 fdtol->fdl_holdcount == 0) {
1836 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1837 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1840 td->td_proc->p_fdtol = NULL;
1841 FILEDESC_XUNLOCK(fdp);
1843 free(fdtol, M_FILEDESC_TO_LEADER);
1845 FILEDESC_XLOCK(fdp);
1846 i = --fdp->fd_refcnt;
1847 FILEDESC_XUNLOCK(fdp);
1851 fpp = fdp->fd_ofiles;
1852 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1854 FILEDESC_XLOCK(fdp);
1857 FILEDESC_XUNLOCK(fdp);
1858 (void) closef(fp, td);
1861 FILEDESC_XLOCK(fdp);
1863 /* XXX This should happen earlier. */
1864 mtx_lock(&fdesc_mtx);
1865 td->td_proc->p_fd = NULL;
1866 mtx_unlock(&fdesc_mtx);
1868 if (fdp->fd_nfiles > NDFILE)
1869 free(fdp->fd_ofiles, M_FILEDESC);
1870 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1871 free(fdp->fd_map, M_FILEDESC);
1875 cdir = fdp->fd_cdir;
1876 fdp->fd_cdir = NULL;
1877 rdir = fdp->fd_rdir;
1878 fdp->fd_rdir = NULL;
1879 jdir = fdp->fd_jdir;
1880 fdp->fd_jdir = NULL;
1881 FILEDESC_XUNLOCK(fdp);
1884 locked = VFS_LOCK_GIANT(cdir->v_mount);
1886 VFS_UNLOCK_GIANT(locked);
1889 locked = VFS_LOCK_GIANT(rdir->v_mount);
1891 VFS_UNLOCK_GIANT(locked);
1894 locked = VFS_LOCK_GIANT(jdir->v_mount);
1896 VFS_UNLOCK_GIANT(locked);
1903 * For setugid programs, we don't want to people to use that setugidness
1904 * to generate error messages which write to a file which otherwise would
1905 * otherwise be off-limits to the process. We check for filesystems where
1906 * the vnode can change out from under us after execve (like [lin]procfs).
1908 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1909 * sufficient. We also don't check for setugidness since we know we are.
1912 is_unsafe(struct file *fp)
1914 if (fp->f_type == DTYPE_VNODE) {
1915 struct vnode *vp = fp->f_vnode;
1917 if ((vp->v_vflag & VV_PROCDEP) != 0)
1924 * Make this setguid thing safe, if at all possible.
1927 setugidsafety(struct thread *td)
1929 struct filedesc *fdp;
1932 /* Certain daemons might not have file descriptors. */
1933 fdp = td->td_proc->p_fd;
1938 * Note: fdp->fd_ofiles may be reallocated out from under us while
1939 * we are blocked in a close. Be careful!
1941 FILEDESC_XLOCK(fdp);
1942 for (i = 0; i <= fdp->fd_lastfile; i++) {
1945 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1948 knote_fdclose(td, i);
1950 * NULL-out descriptor prior to close to avoid
1951 * a race while close blocks.
1953 fp = fdp->fd_ofiles[i];
1954 fdp->fd_ofiles[i] = NULL;
1955 fdp->fd_ofileflags[i] = 0;
1957 FILEDESC_XUNLOCK(fdp);
1958 (void) closef(fp, td);
1959 FILEDESC_XLOCK(fdp);
1962 FILEDESC_XUNLOCK(fdp);
1966 * If a specific file object occupies a specific file descriptor, close the
1967 * file descriptor entry and drop a reference on the file object. This is a
1968 * convenience function to handle a subsequent error in a function that calls
1969 * falloc() that handles the race that another thread might have closed the
1970 * file descriptor out from under the thread creating the file object.
1973 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1976 FILEDESC_XLOCK(fdp);
1977 if (fdp->fd_ofiles[idx] == fp) {
1978 fdp->fd_ofiles[idx] = NULL;
1980 FILEDESC_XUNLOCK(fdp);
1983 FILEDESC_XUNLOCK(fdp);
1987 * Close any files on exec?
1990 fdcloseexec(struct thread *td)
1992 struct filedesc *fdp;
1995 /* Certain daemons might not have file descriptors. */
1996 fdp = td->td_proc->p_fd;
2000 FILEDESC_XLOCK(fdp);
2003 * We cannot cache fd_ofiles or fd_ofileflags since operations
2004 * may block and rip them out from under us.
2006 for (i = 0; i <= fdp->fd_lastfile; i++) {
2007 if (fdp->fd_ofiles[i] != NULL &&
2008 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
2009 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
2012 knote_fdclose(td, i);
2014 * NULL-out descriptor prior to close to avoid
2015 * a race while close blocks.
2017 fp = fdp->fd_ofiles[i];
2018 fdp->fd_ofiles[i] = NULL;
2019 fdp->fd_ofileflags[i] = 0;
2021 if (fp->f_type == DTYPE_MQUEUE)
2022 mq_fdclose(td, i, fp);
2023 FILEDESC_XUNLOCK(fdp);
2024 (void) closef(fp, td);
2025 FILEDESC_XLOCK(fdp);
2028 FILEDESC_XUNLOCK(fdp);
2032 * It is unsafe for set[ug]id processes to be started with file
2033 * descriptors 0..2 closed, as these descriptors are given implicit
2034 * significance in the Standard C library. fdcheckstd() will create a
2035 * descriptor referencing /dev/null for each of stdin, stdout, and
2036 * stderr that is not already open.
2039 fdcheckstd(struct thread *td)
2041 struct filedesc *fdp;
2042 register_t retval, save;
2043 int i, error, devnull;
2045 fdp = td->td_proc->p_fd;
2048 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2051 for (i = 0; i < 3; i++) {
2052 if (fdp->fd_ofiles[i] != NULL)
2055 save = td->td_retval[0];
2056 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2058 devnull = td->td_retval[0];
2059 td->td_retval[0] = save;
2062 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2064 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2073 * Internal form of close. Decrement reference count on file structure.
2074 * Note: td may be NULL when closing a file that was being passed in a
2077 * XXXRW: Giant is not required for the caller, but often will be held; this
2078 * makes it moderately likely the Giant will be recursed in the VFS case.
2081 closef(struct file *fp, struct thread *td)
2085 struct filedesc_to_leader *fdtol;
2086 struct filedesc *fdp;
2089 * POSIX record locking dictates that any close releases ALL
2090 * locks owned by this process. This is handled by setting
2091 * a flag in the unlock to free ONLY locks obeying POSIX
2092 * semantics, and not to free BSD-style file locks.
2093 * If the descriptor was in a message, POSIX-style locks
2094 * aren't passed with the descriptor, and the thread pointer
2095 * will be NULL. Callers should be careful only to pass a
2096 * NULL thread pointer when there really is no owning
2097 * context that might have locks, or the locks will be
2100 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2104 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2105 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2106 lf.l_whence = SEEK_SET;
2109 lf.l_type = F_UNLCK;
2110 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2111 F_UNLCK, &lf, F_POSIX);
2113 fdtol = td->td_proc->p_fdtol;
2114 if (fdtol != NULL) {
2116 * Handle special case where file descriptor table is
2117 * shared between multiple process leaders.
2119 fdp = td->td_proc->p_fd;
2120 FILEDESC_XLOCK(fdp);
2121 for (fdtol = fdtol->fdl_next;
2122 fdtol != td->td_proc->p_fdtol;
2123 fdtol = fdtol->fdl_next) {
2124 if ((fdtol->fdl_leader->p_flag &
2127 fdtol->fdl_holdcount++;
2128 FILEDESC_XUNLOCK(fdp);
2129 lf.l_whence = SEEK_SET;
2132 lf.l_type = F_UNLCK;
2134 (void) VOP_ADVLOCK(vp,
2135 (caddr_t)fdtol->fdl_leader,
2136 F_UNLCK, &lf, F_POSIX);
2137 FILEDESC_XLOCK(fdp);
2138 fdtol->fdl_holdcount--;
2139 if (fdtol->fdl_holdcount == 0 &&
2140 fdtol->fdl_wakeup != 0) {
2141 fdtol->fdl_wakeup = 0;
2145 FILEDESC_XUNLOCK(fdp);
2147 VFS_UNLOCK_GIANT(vfslocked);
2149 return (fdrop(fp, td));
2153 * Initialize the file pointer with the specified properties.
2155 * The ops are set with release semantics to be certain that the flags, type,
2156 * and data are visible when ops is. This is to prevent ops methods from being
2157 * called with bad data.
2160 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2165 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2169 fget_unlocked(struct filedesc *fdp, int fd)
2174 if (fd < 0 || fd >= fdp->fd_nfiles)
2177 * Fetch the descriptor locklessly. We avoid fdrop() races by
2178 * never raising a refcount above 0. To accomplish this we have
2179 * to use a cmpset loop rather than an atomic_add. The descriptor
2180 * must be re-verified once we acquire a reference to be certain
2181 * that the identity is still correct and we did not lose a race
2182 * due to preemption.
2185 fp = fdp->fd_ofiles[fd];
2188 count = fp->f_count;
2192 * Use an acquire barrier to prevent caching of fd_ofiles
2193 * so it is refreshed for verification.
2195 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2197 if (fp == fdp->fd_ofiles[fd])
2199 fdrop(fp, curthread);
2206 * Extract the file pointer associated with the specified descriptor for the
2207 * current user process.
2209 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2212 * If an error occured the non-zero error is returned and *fpp is set to
2213 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2214 * responsible for fdrop().
2217 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2219 struct filedesc *fdp;
2223 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2225 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2227 if (fp->f_ops == &badfileops) {
2232 * FREAD and FWRITE failure return EBADF as per POSIX.
2234 * Only one flag, or 0, may be specified.
2236 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2237 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2246 fget(struct thread *td, int fd, struct file **fpp)
2249 return(_fget(td, fd, fpp, 0));
2253 fget_read(struct thread *td, int fd, struct file **fpp)
2256 return(_fget(td, fd, fpp, FREAD));
2260 fget_write(struct thread *td, int fd, struct file **fpp)
2263 return(_fget(td, fd, fpp, FWRITE));
2267 * Like fget() but loads the underlying vnode, or returns an error if the
2268 * descriptor does not represent a vnode. Note that pipes use vnodes but
2269 * never have VM objects. The returned vnode will be vref()'d.
2271 * XXX: what about the unused flags ?
2274 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2280 if ((error = _fget(td, fd, &fp, flags)) != 0)
2282 if (fp->f_vnode == NULL) {
2294 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2297 return (_fgetvp(td, fd, vpp, 0));
2301 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2304 return (_fgetvp(td, fd, vpp, FREAD));
2309 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2312 return (_fgetvp(td, fd, vpp, FWRITE));
2317 * Like fget() but loads the underlying socket, or returns an error if the
2318 * descriptor does not represent a socket.
2320 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2323 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2324 * on their file descriptor reference to prevent the socket from being free'd
2328 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2336 if ((error = _fget(td, fd, &fp, 0)) != 0)
2338 if (fp->f_type != DTYPE_SOCKET) {
2343 *fflagp = fp->f_flag;
2354 * Drop the reference count on the socket and XXX release the SX lock in the
2355 * future. The last reference closes the socket.
2357 * Note: fputsock() is deprecated, see comment for fgetsock().
2360 fputsock(struct socket *so)
2365 CURVNET_SET(so->so_vnet);
2371 * Handle the last reference to a file being closed.
2374 _fdrop(struct file *fp, struct thread *td)
2379 if (fp->f_count != 0)
2380 panic("fdrop: count %d", fp->f_count);
2381 if (fp->f_ops != &badfileops)
2382 error = fo_close(fp, td);
2383 atomic_subtract_int(&openfiles, 1);
2385 free(fp->f_advice, M_FADVISE);
2386 uma_zfree(file_zone, fp);
2392 * Apply an advisory lock on a file descriptor.
2394 * Just attempt to get a record lock of the requested type on the entire file
2395 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2397 #ifndef _SYS_SYSPROTO_H_
2405 flock(struct thread *td, struct flock_args *uap)
2413 if ((error = fget(td, uap->fd, &fp)) != 0)
2415 if (fp->f_type != DTYPE_VNODE) {
2417 return (EOPNOTSUPP);
2421 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2422 lf.l_whence = SEEK_SET;
2425 if (uap->how & LOCK_UN) {
2426 lf.l_type = F_UNLCK;
2427 atomic_clear_int(&fp->f_flag, FHASLOCK);
2428 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2431 if (uap->how & LOCK_EX)
2432 lf.l_type = F_WRLCK;
2433 else if (uap->how & LOCK_SH)
2434 lf.l_type = F_RDLCK;
2439 atomic_set_int(&fp->f_flag, FHASLOCK);
2440 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2441 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2444 VFS_UNLOCK_GIANT(vfslocked);
2448 * Duplicate the specified descriptor to a free descriptor.
2451 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2457 * If the to-be-dup'd fd number is greater than the allowed number
2458 * of file descriptors, or the fd to be dup'd has already been
2459 * closed, then reject.
2461 FILEDESC_XLOCK(fdp);
2462 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2463 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2464 FILEDESC_XUNLOCK(fdp);
2469 * There are two cases of interest here.
2471 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2473 * For ENXIO steal away the file structure from (dfd) and store it in
2474 * (indx). (dfd) is effectively closed by this operation.
2476 * Any other error code is just returned.
2481 * Check that the mode the file is being opened for is a
2482 * subset of the mode of the existing descriptor.
2484 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2485 FILEDESC_XUNLOCK(fdp);
2488 fp = fdp->fd_ofiles[indx];
2489 fdp->fd_ofiles[indx] = wfp;
2490 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2494 FILEDESC_XUNLOCK(fdp);
2497 * We now own the reference to fp that the ofiles[]
2498 * array used to own. Release it.
2505 * Steal away the file pointer from dfd and stuff it into indx.
2507 fp = fdp->fd_ofiles[indx];
2508 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2509 fdp->fd_ofiles[dfd] = NULL;
2510 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2511 fdp->fd_ofileflags[dfd] = 0;
2515 FILEDESC_XUNLOCK(fdp);
2518 * We now own the reference to fp that the ofiles[] array
2519 * used to own. Release it.
2526 FILEDESC_XUNLOCK(fdp);
2533 * Scan all active processes and prisons to see if any of them have a current
2534 * or root directory of `olddp'. If so, replace them with the new mount point.
2537 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2539 struct filedesc *fdp;
2544 if (vrefcnt(olddp) == 1)
2547 sx_slock(&allproc_lock);
2548 FOREACH_PROC_IN_SYSTEM(p) {
2552 FILEDESC_XLOCK(fdp);
2553 if (fdp->fd_cdir == olddp) {
2555 fdp->fd_cdir = newdp;
2558 if (fdp->fd_rdir == olddp) {
2560 fdp->fd_rdir = newdp;
2563 if (fdp->fd_jdir == olddp) {
2565 fdp->fd_jdir = newdp;
2568 FILEDESC_XUNLOCK(fdp);
2571 sx_sunlock(&allproc_lock);
2572 if (rootvnode == olddp) {
2577 mtx_lock(&prison0.pr_mtx);
2578 if (prison0.pr_root == olddp) {
2580 prison0.pr_root = newdp;
2583 mtx_unlock(&prison0.pr_mtx);
2584 sx_slock(&allprison_lock);
2585 TAILQ_FOREACH(pr, &allprison, pr_list) {
2586 mtx_lock(&pr->pr_mtx);
2587 if (pr->pr_root == olddp) {
2589 pr->pr_root = newdp;
2592 mtx_unlock(&pr->pr_mtx);
2594 sx_sunlock(&allprison_lock);
2599 struct filedesc_to_leader *
2600 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2602 struct filedesc_to_leader *fdtol;
2604 fdtol = malloc(sizeof(struct filedesc_to_leader),
2605 M_FILEDESC_TO_LEADER,
2607 fdtol->fdl_refcount = 1;
2608 fdtol->fdl_holdcount = 0;
2609 fdtol->fdl_wakeup = 0;
2610 fdtol->fdl_leader = leader;
2612 FILEDESC_XLOCK(fdp);
2613 fdtol->fdl_next = old->fdl_next;
2614 fdtol->fdl_prev = old;
2615 old->fdl_next = fdtol;
2616 fdtol->fdl_next->fdl_prev = fdtol;
2617 FILEDESC_XUNLOCK(fdp);
2619 fdtol->fdl_next = fdtol;
2620 fdtol->fdl_prev = fdtol;
2626 * Get file structures globally.
2629 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2632 struct filedesc *fdp;
2637 error = sysctl_wire_old_buffer(req, 0);
2640 if (req->oldptr == NULL) {
2642 sx_slock(&allproc_lock);
2643 FOREACH_PROC_IN_SYSTEM(p) {
2644 if (p->p_state == PRS_NEW)
2649 /* overestimates sparse tables. */
2650 if (fdp->fd_lastfile > 0)
2651 n += fdp->fd_lastfile;
2654 sx_sunlock(&allproc_lock);
2655 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2658 bzero(&xf, sizeof(xf));
2659 xf.xf_size = sizeof(xf);
2660 sx_slock(&allproc_lock);
2661 FOREACH_PROC_IN_SYSTEM(p) {
2663 if (p->p_state == PRS_NEW) {
2667 if (p_cansee(req->td, p) != 0) {
2671 xf.xf_pid = p->p_pid;
2672 xf.xf_uid = p->p_ucred->cr_uid;
2677 FILEDESC_SLOCK(fdp);
2678 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2679 if ((fp = fdp->fd_ofiles[n]) == NULL)
2683 xf.xf_data = fp->f_data;
2684 xf.xf_vnode = fp->f_vnode;
2685 xf.xf_type = fp->f_type;
2686 xf.xf_count = fp->f_count;
2688 xf.xf_offset = fp->f_offset;
2689 xf.xf_flag = fp->f_flag;
2690 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2694 FILEDESC_SUNLOCK(fdp);
2699 sx_sunlock(&allproc_lock);
2703 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2704 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2706 #ifdef KINFO_OFILE_SIZE
2707 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2710 #ifdef COMPAT_FREEBSD7
2712 export_vnode_for_osysctl(struct vnode *vp, int type,
2713 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2716 char *fullpath, *freepath;
2719 bzero(kif, sizeof(*kif));
2720 kif->kf_structsize = sizeof(*kif);
2724 kif->kf_type = KF_TYPE_VNODE;
2725 /* This function only handles directories. */
2726 if (vp->v_type != VDIR) {
2730 kif->kf_vnode_type = KF_VTYPE_VDIR;
2733 * This is not a true file descriptor, so we set a bogus refcount
2734 * and offset to indicate these fields should be ignored.
2736 kif->kf_ref_count = -1;
2737 kif->kf_offset = -1;
2741 FILEDESC_SUNLOCK(fdp);
2742 vn_fullpath(curthread, vp, &fullpath, &freepath);
2743 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2745 VFS_UNLOCK_GIANT(vfslocked);
2746 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2747 if (freepath != NULL)
2748 free(freepath, M_TEMP);
2749 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2750 FILEDESC_SLOCK(fdp);
2755 * Get per-process file descriptors for use by procstat(1), et al.
2758 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2760 char *fullpath, *freepath;
2761 struct kinfo_ofile *kif;
2762 struct filedesc *fdp;
2763 int error, i, *name;
2764 struct shmfd *shmfd;
2773 if ((p = pfind((pid_t)name[0])) == NULL)
2775 if ((error = p_candebug(curthread, p))) {
2783 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2784 FILEDESC_SLOCK(fdp);
2785 if (fdp->fd_cdir != NULL)
2786 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2788 if (fdp->fd_rdir != NULL)
2789 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2791 if (fdp->fd_jdir != NULL)
2792 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2794 for (i = 0; i < fdp->fd_nfiles; i++) {
2795 if ((fp = fdp->fd_ofiles[i]) == NULL)
2797 bzero(kif, sizeof(*kif));
2798 kif->kf_structsize = sizeof(*kif);
2804 switch (fp->f_type) {
2806 kif->kf_type = KF_TYPE_VNODE;
2811 kif->kf_type = KF_TYPE_SOCKET;
2816 kif->kf_type = KF_TYPE_PIPE;
2820 kif->kf_type = KF_TYPE_FIFO;
2825 kif->kf_type = KF_TYPE_KQUEUE;
2829 kif->kf_type = KF_TYPE_CRYPTO;
2833 kif->kf_type = KF_TYPE_MQUEUE;
2837 kif->kf_type = KF_TYPE_SHM;
2842 kif->kf_type = KF_TYPE_SEM;
2846 kif->kf_type = KF_TYPE_PTS;
2851 kif->kf_type = KF_TYPE_UNKNOWN;
2854 kif->kf_ref_count = fp->f_count;
2855 if (fp->f_flag & FREAD)
2856 kif->kf_flags |= KF_FLAG_READ;
2857 if (fp->f_flag & FWRITE)
2858 kif->kf_flags |= KF_FLAG_WRITE;
2859 if (fp->f_flag & FAPPEND)
2860 kif->kf_flags |= KF_FLAG_APPEND;
2861 if (fp->f_flag & FASYNC)
2862 kif->kf_flags |= KF_FLAG_ASYNC;
2863 if (fp->f_flag & FFSYNC)
2864 kif->kf_flags |= KF_FLAG_FSYNC;
2865 if (fp->f_flag & FNONBLOCK)
2866 kif->kf_flags |= KF_FLAG_NONBLOCK;
2867 if (fp->f_flag & O_DIRECT)
2868 kif->kf_flags |= KF_FLAG_DIRECT;
2869 if (fp->f_flag & FHASLOCK)
2870 kif->kf_flags |= KF_FLAG_HASLOCK;
2871 kif->kf_offset = fp->f_offset;
2874 switch (vp->v_type) {
2876 kif->kf_vnode_type = KF_VTYPE_VNON;
2879 kif->kf_vnode_type = KF_VTYPE_VREG;
2882 kif->kf_vnode_type = KF_VTYPE_VDIR;
2885 kif->kf_vnode_type = KF_VTYPE_VBLK;
2888 kif->kf_vnode_type = KF_VTYPE_VCHR;
2891 kif->kf_vnode_type = KF_VTYPE_VLNK;
2894 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2897 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2900 kif->kf_vnode_type = KF_VTYPE_VBAD;
2903 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2907 * It is OK to drop the filedesc lock here as we will
2908 * re-validate and re-evaluate its properties when
2909 * the loop continues.
2913 FILEDESC_SUNLOCK(fdp);
2914 vn_fullpath(curthread, vp, &fullpath, &freepath);
2915 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2917 VFS_UNLOCK_GIANT(vfslocked);
2918 strlcpy(kif->kf_path, fullpath,
2919 sizeof(kif->kf_path));
2920 if (freepath != NULL)
2921 free(freepath, M_TEMP);
2922 FILEDESC_SLOCK(fdp);
2925 struct sockaddr *sa;
2927 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2928 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2929 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2932 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2933 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2934 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2937 kif->kf_sock_domain =
2938 so->so_proto->pr_domain->dom_family;
2939 kif->kf_sock_type = so->so_type;
2940 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2943 strlcpy(kif->kf_path, tty_devname(tp),
2944 sizeof(kif->kf_path));
2947 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
2948 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2952 FILEDESC_SUNLOCK(fdp);
2958 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2959 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2960 #endif /* COMPAT_FREEBSD7 */
2962 #ifdef KINFO_FILE_SIZE
2963 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2967 export_vnode_for_sysctl(struct vnode *vp, int type,
2968 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2971 char *fullpath, *freepath;
2974 bzero(kif, sizeof(*kif));
2978 kif->kf_type = KF_TYPE_VNODE;
2979 /* This function only handles directories. */
2980 if (vp->v_type != VDIR) {
2984 kif->kf_vnode_type = KF_VTYPE_VDIR;
2987 * This is not a true file descriptor, so we set a bogus refcount
2988 * and offset to indicate these fields should be ignored.
2990 kif->kf_ref_count = -1;
2991 kif->kf_offset = -1;
2995 FILEDESC_SUNLOCK(fdp);
2996 vn_fullpath(curthread, vp, &fullpath, &freepath);
2997 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2999 VFS_UNLOCK_GIANT(vfslocked);
3000 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3001 if (freepath != NULL)
3002 free(freepath, M_TEMP);
3003 /* Pack record size down */
3004 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3005 strlen(kif->kf_path) + 1;
3006 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3007 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3008 FILEDESC_SLOCK(fdp);
3013 * Get per-process file descriptors for use by procstat(1), et al.
3016 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3018 char *fullpath, *freepath;
3019 struct kinfo_file *kif;
3020 struct filedesc *fdp;
3021 int error, i, *name;
3022 struct shmfd *shmfd;
3032 if ((p = pfind((pid_t)name[0])) == NULL)
3034 if ((error = p_candebug(curthread, p))) {
3042 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3043 FILEDESC_SLOCK(fdp);
3044 if (fdp->fd_cdir != NULL)
3045 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3047 if (fdp->fd_rdir != NULL)
3048 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3050 if (fdp->fd_jdir != NULL)
3051 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3053 for (i = 0; i < fdp->fd_nfiles; i++) {
3054 if ((fp = fdp->fd_ofiles[i]) == NULL)
3056 bzero(kif, sizeof(*kif));
3062 switch (fp->f_type) {
3064 kif->kf_type = KF_TYPE_VNODE;
3069 kif->kf_type = KF_TYPE_SOCKET;
3074 kif->kf_type = KF_TYPE_PIPE;
3078 kif->kf_type = KF_TYPE_FIFO;
3083 kif->kf_type = KF_TYPE_KQUEUE;
3087 kif->kf_type = KF_TYPE_CRYPTO;
3091 kif->kf_type = KF_TYPE_MQUEUE;
3095 kif->kf_type = KF_TYPE_SHM;
3100 kif->kf_type = KF_TYPE_SEM;
3104 kif->kf_type = KF_TYPE_PTS;
3109 kif->kf_type = KF_TYPE_UNKNOWN;
3112 kif->kf_ref_count = fp->f_count;
3113 if (fp->f_flag & FREAD)
3114 kif->kf_flags |= KF_FLAG_READ;
3115 if (fp->f_flag & FWRITE)
3116 kif->kf_flags |= KF_FLAG_WRITE;
3117 if (fp->f_flag & FAPPEND)
3118 kif->kf_flags |= KF_FLAG_APPEND;
3119 if (fp->f_flag & FASYNC)
3120 kif->kf_flags |= KF_FLAG_ASYNC;
3121 if (fp->f_flag & FFSYNC)
3122 kif->kf_flags |= KF_FLAG_FSYNC;
3123 if (fp->f_flag & FNONBLOCK)
3124 kif->kf_flags |= KF_FLAG_NONBLOCK;
3125 if (fp->f_flag & O_DIRECT)
3126 kif->kf_flags |= KF_FLAG_DIRECT;
3127 if (fp->f_flag & FHASLOCK)
3128 kif->kf_flags |= KF_FLAG_HASLOCK;
3129 kif->kf_offset = fp->f_offset;
3132 switch (vp->v_type) {
3134 kif->kf_vnode_type = KF_VTYPE_VNON;
3137 kif->kf_vnode_type = KF_VTYPE_VREG;
3140 kif->kf_vnode_type = KF_VTYPE_VDIR;
3143 kif->kf_vnode_type = KF_VTYPE_VBLK;
3146 kif->kf_vnode_type = KF_VTYPE_VCHR;
3149 kif->kf_vnode_type = KF_VTYPE_VLNK;
3152 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3155 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3158 kif->kf_vnode_type = KF_VTYPE_VBAD;
3161 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3165 * It is OK to drop the filedesc lock here as we will
3166 * re-validate and re-evaluate its properties when
3167 * the loop continues.
3171 FILEDESC_SUNLOCK(fdp);
3172 vn_fullpath(curthread, vp, &fullpath, &freepath);
3173 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3175 VFS_UNLOCK_GIANT(vfslocked);
3176 strlcpy(kif->kf_path, fullpath,
3177 sizeof(kif->kf_path));
3178 if (freepath != NULL)
3179 free(freepath, M_TEMP);
3180 FILEDESC_SLOCK(fdp);
3183 struct sockaddr *sa;
3185 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3186 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3187 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3190 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3191 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3192 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3195 kif->kf_sock_domain =
3196 so->so_proto->pr_domain->dom_family;
3197 kif->kf_sock_type = so->so_type;
3198 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3201 strlcpy(kif->kf_path, tty_devname(tp),
3202 sizeof(kif->kf_path));
3205 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3206 /* Pack record size down */
3207 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3208 strlen(kif->kf_path) + 1;
3209 kif->kf_structsize = roundup(kif->kf_structsize,
3211 oldidx = req->oldidx;
3212 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3214 if (error == ENOMEM) {
3216 * The hack to keep the ABI of sysctl
3217 * kern.proc.filedesc intact, but not
3218 * to account a partially copied
3219 * kinfo_file into the oldidx.
3221 req->oldidx = oldidx;
3227 FILEDESC_SUNLOCK(fdp);
3233 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3234 sysctl_kern_proc_filedesc, "Process filedesc entries");
3238 * For the purposes of debugging, generate a human-readable string for the
3242 file_type_to_name(short type)
3272 * For the purposes of debugging, identify a process (if any, perhaps one of
3273 * many) that references the passed file in its file descriptor array. Return
3276 static struct proc *
3277 file_to_first_proc(struct file *fp)
3279 struct filedesc *fdp;
3283 FOREACH_PROC_IN_SYSTEM(p) {
3284 if (p->p_state == PRS_NEW)
3289 for (n = 0; n < fdp->fd_nfiles; n++) {
3290 if (fp == fdp->fd_ofiles[n])
3298 db_print_file(struct file *fp, int header)
3303 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3304 "File", "Type", "Data", "Flag", "GCFl", "Count",
3305 "MCount", "Vnode", "FPID", "FCmd");
3306 p = file_to_first_proc(fp);
3307 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3308 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3309 0, fp->f_count, 0, fp->f_vnode,
3310 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3313 DB_SHOW_COMMAND(file, db_show_file)
3318 db_printf("usage: show file <addr>\n");
3321 fp = (struct file *)addr;
3322 db_print_file(fp, 1);
3325 DB_SHOW_COMMAND(files, db_show_files)
3327 struct filedesc *fdp;
3334 FOREACH_PROC_IN_SYSTEM(p) {
3335 if (p->p_state == PRS_NEW)
3337 if ((fdp = p->p_fd) == NULL)
3339 for (n = 0; n < fdp->fd_nfiles; ++n) {
3340 if ((fp = fdp->fd_ofiles[n]) == NULL)
3342 db_print_file(fp, header);
3349 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3350 &maxfilesperproc, 0, "Maximum files allowed open per process");
3352 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3353 &maxfiles, 0, "Maximum number of files");
3355 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3356 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3360 filelistinit(void *dummy)
3363 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3364 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3365 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3366 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3368 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3370 /*-------------------------------------------------------------------*/
3373 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3380 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3387 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3394 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3401 badfo_kqfilter(struct file *fp, struct knote *kn)
3408 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3415 badfo_close(struct file *fp, struct thread *td)
3421 struct fileops badfileops = {
3422 .fo_read = badfo_readwrite,
3423 .fo_write = badfo_readwrite,
3424 .fo_truncate = badfo_truncate,
3425 .fo_ioctl = badfo_ioctl,
3426 .fo_poll = badfo_poll,
3427 .fo_kqfilter = badfo_kqfilter,
3428 .fo_stat = badfo_stat,
3429 .fo_close = badfo_close,
3433 /*-------------------------------------------------------------------*/
3436 * File Descriptor pseudo-device driver (/dev/fd/).
3438 * Opening minor device N dup()s the file (if any) connected to file
3439 * descriptor N belonging to the calling process. Note that this driver
3440 * consists of only the ``open()'' routine, because all subsequent
3441 * references to this file will be direct to the other driver.
3443 * XXX: we could give this one a cloning event handler if necessary.
3448 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3452 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3453 * the file descriptor being sought for duplication. The error
3454 * return ensures that the vnode for this device will be released
3455 * by vn_open. Open will detect this special error and take the
3456 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3457 * will simply report the error.
3459 td->td_dupfd = dev2unit(dev);
3463 static struct cdevsw fildesc_cdevsw = {
3464 .d_version = D_VERSION,
3470 fildesc_drvinit(void *unused)
3474 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3475 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3476 make_dev_alias(dev, "stdin");
3477 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3478 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3479 make_dev_alias(dev, "stdout");
3480 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3481 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3482 make_dev_alias(dev, "stderr");
3485 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);