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>
58 #include <sys/mount.h>
59 #include <sys/mqueue.h>
60 #include <sys/mutex.h>
61 #include <sys/namei.h>
64 #include <sys/protosw.h>
65 #include <sys/resourcevar.h>
66 #include <sys/signalvar.h>
67 #include <sys/socketvar.h>
70 #include <sys/syscallsubr.h>
71 #include <sys/sysctl.h>
72 #include <sys/sysproto.h>
74 #include <sys/unistd.h>
76 #include <sys/vnode.h>
78 #include <sys/ktrace.h>
83 #include <security/audit/audit.h>
89 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
90 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
91 "file desc to leader structures");
92 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
94 static uma_zone_t file_zone;
97 /* Flags for do_dup() */
98 #define DUP_FIXED 0x1 /* Force fixed allocation */
99 #define DUP_FCNTL 0x2 /* fcntl()-style errors */
101 static int do_dup(struct thread *td, int flags, int old, int new,
103 static int fd_first_free(struct filedesc *, int, int);
104 static int fd_last_used(struct filedesc *, int, int);
105 static void fdgrowtable(struct filedesc *, int);
106 static void fdunused(struct filedesc *fdp, int fd);
107 static void fdused(struct filedesc *fdp, int fd);
110 * A process is initially started out with NDFILE descriptors stored within
111 * this structure, selected to be enough for typical applications based on
112 * the historical limit of 20 open files (and the usage of descriptors by
113 * shells). If these descriptors are exhausted, a larger descriptor table
114 * may be allocated, up to a process' resource limit; the internal arrays
118 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
119 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
120 #define NDSLOT(x) ((x) / NDENTRIES)
121 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
122 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
125 * Storage required per open file descriptor.
127 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
130 * Storage to hold unused ofiles that need to be reclaimed.
133 struct file **ft_table;
134 SLIST_ENTRY(freetable) ft_next;
138 * Basic allocation of descriptors:
139 * one of the above, plus arrays for NDFILE descriptors.
142 struct filedesc fd_fd;
144 * ofiles which need to be reclaimed on free.
146 SLIST_HEAD(,freetable) fd_free;
148 * These arrays are used when the number of open files is
149 * <= NDFILE, and are then pointed to by the pointers above.
151 struct file *fd_dfiles[NDFILE];
152 char fd_dfileflags[NDFILE];
153 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
157 * Descriptor management.
159 volatile int openfiles; /* actual number of open files */
160 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
161 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
163 /* A mutex to protect the association between a proc and filedesc. */
164 static struct mtx fdesc_mtx;
167 * Find the first zero bit in the given bitmap, starting at low and not
168 * exceeding size - 1.
171 fd_first_free(struct filedesc *fdp, int low, int size)
173 NDSLOTTYPE *map = fdp->fd_map;
181 if (low % NDENTRIES) {
182 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
183 if ((mask &= ~map[off]) != 0UL)
184 return (off * NDENTRIES + ffsl(mask) - 1);
187 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
188 if (map[off] != ~0UL)
189 return (off * NDENTRIES + ffsl(~map[off]) - 1);
194 * Find the highest non-zero bit in the given bitmap, starting at low and
195 * not exceeding size - 1.
198 fd_last_used(struct filedesc *fdp, int low, int size)
200 NDSLOTTYPE *map = fdp->fd_map;
208 if (size % NDENTRIES) {
209 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
210 if ((mask &= map[off]) != 0)
211 return (off * NDENTRIES + flsl(mask) - 1);
214 for (minoff = NDSLOT(low); off >= minoff; --off)
216 return (off * NDENTRIES + flsl(map[off]) - 1);
221 fdisused(struct filedesc *fdp, int fd)
223 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
224 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
225 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
229 * Mark a file descriptor as used.
232 fdused(struct filedesc *fdp, int fd)
235 FILEDESC_XLOCK_ASSERT(fdp);
236 KASSERT(!fdisused(fdp, fd),
237 ("fd already used"));
239 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
240 if (fd > fdp->fd_lastfile)
241 fdp->fd_lastfile = fd;
242 if (fd == fdp->fd_freefile)
243 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
247 * Mark a file descriptor as unused.
250 fdunused(struct filedesc *fdp, int fd)
253 FILEDESC_XLOCK_ASSERT(fdp);
254 KASSERT(fdisused(fdp, fd),
255 ("fd is already unused"));
256 KASSERT(fdp->fd_ofiles[fd] == NULL,
257 ("fd is still in use"));
259 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
260 if (fd < fdp->fd_freefile)
261 fdp->fd_freefile = fd;
262 if (fd == fdp->fd_lastfile)
263 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
267 * System calls on descriptors.
269 #ifndef _SYS_SYSPROTO_H_
270 struct getdtablesize_args {
276 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
278 struct proc *p = td->td_proc;
282 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
288 * Duplicate a file descriptor to a particular value.
290 * Note: keep in mind that a potential race condition exists when closing
291 * descriptors from a shared descriptor table (via rfork).
293 #ifndef _SYS_SYSPROTO_H_
301 dup2(struct thread *td, struct dup2_args *uap)
304 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
309 * Duplicate a file descriptor.
311 #ifndef _SYS_SYSPROTO_H_
318 dup(struct thread *td, struct dup_args *uap)
321 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
325 * The file control system call.
327 #ifndef _SYS_SYSPROTO_H_
336 fcntl(struct thread *td, struct fcntl_args *uap)
351 * Convert old flock structure to new.
353 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
354 fl.l_start = ofl.l_start;
355 fl.l_len = ofl.l_len;
356 fl.l_pid = ofl.l_pid;
357 fl.l_type = ofl.l_type;
358 fl.l_whence = ofl.l_whence;
378 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
387 error = kern_fcntl(td, uap->fd, cmd, arg);
390 if (uap->cmd == F_OGETLK) {
391 ofl.l_start = fl.l_start;
392 ofl.l_len = fl.l_len;
393 ofl.l_pid = fl.l_pid;
394 ofl.l_type = fl.l_type;
395 ofl.l_whence = fl.l_whence;
396 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
397 } else if (uap->cmd == F_GETLK) {
398 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
403 static inline struct file *
404 fdtofp(int fd, struct filedesc *fdp)
408 FILEDESC_LOCK_ASSERT(fdp);
409 if ((unsigned)fd >= fdp->fd_nfiles ||
410 (fp = fdp->fd_ofiles[fd]) == NULL)
416 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
418 struct filedesc *fdp;
438 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
443 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
448 if ((fp = fdtofp(fd, fdp)) == NULL) {
449 FILEDESC_SUNLOCK(fdp);
453 pop = &fdp->fd_ofileflags[fd];
454 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
455 FILEDESC_SUNLOCK(fdp);
460 if ((fp = fdtofp(fd, fdp)) == NULL) {
461 FILEDESC_XUNLOCK(fdp);
465 pop = &fdp->fd_ofileflags[fd];
466 *pop = (*pop &~ UF_EXCLOSE) |
467 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
468 FILEDESC_XUNLOCK(fdp);
473 if ((fp = fdtofp(fd, fdp)) == NULL) {
474 FILEDESC_SUNLOCK(fdp);
478 td->td_retval[0] = OFLAGS(fp->f_flag);
479 FILEDESC_SUNLOCK(fdp);
484 if ((fp = fdtofp(fd, fdp)) == NULL) {
485 FILEDESC_SUNLOCK(fdp);
490 FILEDESC_SUNLOCK(fdp);
492 tmp = flg = fp->f_flag;
494 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
495 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
496 tmp = fp->f_flag & FNONBLOCK;
497 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
502 tmp = fp->f_flag & FASYNC;
503 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
508 atomic_clear_int(&fp->f_flag, FNONBLOCK);
510 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
516 if ((fp = fdtofp(fd, fdp)) == NULL) {
517 FILEDESC_SUNLOCK(fdp);
522 FILEDESC_SUNLOCK(fdp);
523 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
525 td->td_retval[0] = tmp;
531 if ((fp = fdtofp(fd, fdp)) == NULL) {
532 FILEDESC_SUNLOCK(fdp);
537 FILEDESC_SUNLOCK(fdp);
539 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
544 error = priv_check(td, PRIV_NFS_LOCKD);
552 /* FALLTHROUGH F_SETLK */
557 if ((fp = fdtofp(fd, fdp)) == NULL) {
558 FILEDESC_SUNLOCK(fdp);
562 if (fp->f_type != DTYPE_VNODE) {
563 FILEDESC_SUNLOCK(fdp);
567 flp = (struct flock *)arg;
568 if (flp->l_whence == SEEK_CUR) {
569 if (fp->f_offset < 0 ||
571 fp->f_offset > OFF_MAX - flp->l_start)) {
572 FILEDESC_SUNLOCK(fdp);
576 flp->l_start += fp->f_offset;
580 * VOP_ADVLOCK() may block.
583 FILEDESC_SUNLOCK(fdp);
585 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
586 switch (flp->l_type) {
588 if ((fp->f_flag & FREAD) == 0) {
592 PROC_LOCK(p->p_leader);
593 p->p_leader->p_flag |= P_ADVLOCK;
594 PROC_UNLOCK(p->p_leader);
595 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
599 if ((fp->f_flag & FWRITE) == 0) {
603 PROC_LOCK(p->p_leader);
604 p->p_leader->p_flag |= P_ADVLOCK;
605 PROC_UNLOCK(p->p_leader);
606 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
610 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
615 * Temporary api for testing remote lock
618 if (flg != F_REMOTE) {
622 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
623 F_UNLCKSYS, flp, flg);
629 VFS_UNLOCK_GIANT(vfslocked);
631 /* Check for race with close */
633 if ((unsigned) fd >= fdp->fd_nfiles ||
634 fp != fdp->fd_ofiles[fd]) {
635 FILEDESC_SUNLOCK(fdp);
636 flp->l_whence = SEEK_SET;
639 flp->l_type = F_UNLCK;
640 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
641 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
642 F_UNLCK, flp, F_POSIX);
643 VFS_UNLOCK_GIANT(vfslocked);
646 FILEDESC_SUNLOCK(fdp);
652 if ((fp = fdtofp(fd, fdp)) == NULL) {
653 FILEDESC_SUNLOCK(fdp);
657 if (fp->f_type != DTYPE_VNODE) {
658 FILEDESC_SUNLOCK(fdp);
662 flp = (struct flock *)arg;
663 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
664 flp->l_type != F_UNLCK) {
665 FILEDESC_SUNLOCK(fdp);
669 if (flp->l_whence == SEEK_CUR) {
670 if ((flp->l_start > 0 &&
671 fp->f_offset > OFF_MAX - flp->l_start) ||
673 fp->f_offset < OFF_MIN - flp->l_start)) {
674 FILEDESC_SUNLOCK(fdp);
678 flp->l_start += fp->f_offset;
681 * VOP_ADVLOCK() may block.
684 FILEDESC_SUNLOCK(fdp);
686 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
687 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
689 VFS_UNLOCK_GIANT(vfslocked);
695 arg = arg ? 128 * 1024: 0;
699 if ((fp = fdtofp(fd, fdp)) == NULL) {
700 FILEDESC_SUNLOCK(fdp);
704 if (fp->f_type != DTYPE_VNODE) {
705 FILEDESC_SUNLOCK(fdp);
710 FILEDESC_SUNLOCK(fdp);
713 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
714 error = vn_lock(vp, LK_SHARED);
716 goto readahead_vnlock_fail;
717 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
719 fp->f_seqcount = (arg + bsize - 1) / bsize;
721 new = old = fp->f_flag;
723 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
724 readahead_vnlock_fail:
725 VFS_UNLOCK_GIANT(vfslocked);
729 new = old = fp->f_flag;
731 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
740 VFS_UNLOCK_GIANT(vfslocked);
745 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
748 do_dup(struct thread *td, int flags, int old, int new,
751 struct filedesc *fdp;
755 int error, holdleaders, maxfd;
761 * Verify we have a valid descriptor to dup from and possibly to
762 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
763 * return EINVAL when the new descriptor is out of bounds.
768 return (flags & DUP_FCNTL ? EINVAL : EBADF);
770 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
773 return (flags & DUP_FCNTL ? EINVAL : EMFILE);
776 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
777 FILEDESC_XUNLOCK(fdp);
780 if (flags & DUP_FIXED && old == new) {
782 FILEDESC_XUNLOCK(fdp);
785 fp = fdp->fd_ofiles[old];
789 * If the caller specified a file descriptor, make sure the file
790 * table is large enough to hold it, and grab it. Otherwise, just
791 * allocate a new descriptor the usual way. Since the filedesc
792 * lock may be temporarily dropped in the process, we have to look
795 if (flags & DUP_FIXED) {
796 if (new >= fdp->fd_nfiles)
797 fdgrowtable(fdp, new + 1);
798 if (fdp->fd_ofiles[new] == NULL)
801 if ((error = fdalloc(td, new, &new)) != 0) {
802 FILEDESC_XUNLOCK(fdp);
809 * If the old file changed out from under us then treat it as a
810 * bad file descriptor. Userland should do its own locking to
813 if (fdp->fd_ofiles[old] != fp) {
814 /* we've allocated a descriptor which we won't use */
815 if (fdp->fd_ofiles[new] == NULL)
817 FILEDESC_XUNLOCK(fdp);
822 ("new fd is same as old"));
825 * Save info on the descriptor being overwritten. We cannot close
826 * it without introducing an ownership race for the slot, since we
827 * need to drop the filedesc lock to call closef().
829 * XXX this duplicates parts of close().
831 delfp = fdp->fd_ofiles[new];
834 if (td->td_proc->p_fdtol != NULL) {
836 * Ask fdfree() to sleep to ensure that all relevant
837 * process leaders can be traversed in closef().
839 fdp->fd_holdleaderscount++;
845 * Duplicate the source descriptor
847 fdp->fd_ofiles[new] = fp;
848 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
849 if (new > fdp->fd_lastfile)
850 fdp->fd_lastfile = new;
854 * If we dup'd over a valid file, we now own the reference to it
855 * and must dispose of it using closef() semantics (as if a
856 * close() were performed on it).
858 * XXX this duplicates parts of close().
861 knote_fdclose(td, new);
862 if (delfp->f_type == DTYPE_MQUEUE)
863 mq_fdclose(td, new, delfp);
864 FILEDESC_XUNLOCK(fdp);
865 (void) closef(delfp, td);
868 fdp->fd_holdleaderscount--;
869 if (fdp->fd_holdleaderscount == 0 &&
870 fdp->fd_holdleaderswakeup != 0) {
871 fdp->fd_holdleaderswakeup = 0;
872 wakeup(&fdp->fd_holdleaderscount);
874 FILEDESC_XUNLOCK(fdp);
877 FILEDESC_XUNLOCK(fdp);
883 * If sigio is on the list associated with a process or process group,
884 * disable signalling from the device, remove sigio from the list and
888 funsetown(struct sigio **sigiop)
898 *(sigio->sio_myref) = NULL;
899 if ((sigio)->sio_pgid < 0) {
900 struct pgrp *pg = (sigio)->sio_pgrp;
902 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
906 struct proc *p = (sigio)->sio_proc;
908 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
913 crfree(sigio->sio_ucred);
914 free(sigio, M_SIGIO);
918 * Free a list of sigio structures.
919 * We only need to lock the SIGIO_LOCK because we have made ourselves
920 * inaccessible to callers of fsetown and therefore do not need to lock
921 * the proc or pgrp struct for the list manipulation.
924 funsetownlst(struct sigiolst *sigiolst)
930 sigio = SLIST_FIRST(sigiolst);
937 * Every entry of the list should belong
938 * to a single proc or pgrp.
940 if (sigio->sio_pgid < 0) {
941 pg = sigio->sio_pgrp;
942 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
943 } else /* if (sigio->sio_pgid > 0) */ {
945 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
949 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
950 *(sigio->sio_myref) = NULL;
952 KASSERT(sigio->sio_pgid < 0,
953 ("Proc sigio in pgrp sigio list"));
954 KASSERT(sigio->sio_pgrp == pg,
955 ("Bogus pgrp in sigio list"));
957 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
960 } else /* if (p != NULL) */ {
961 KASSERT(sigio->sio_pgid > 0,
962 ("Pgrp sigio in proc sigio list"));
963 KASSERT(sigio->sio_proc == p,
964 ("Bogus proc in sigio list"));
966 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
971 crfree(sigio->sio_ucred);
972 free(sigio, M_SIGIO);
979 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
981 * After permission checking, add a sigio structure to the sigio list for
982 * the process or process group.
985 fsetown(pid_t pgid, struct sigio **sigiop)
999 /* Allocate and fill in the new sigio out of locks. */
1000 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1001 sigio->sio_pgid = pgid;
1002 sigio->sio_ucred = crhold(curthread->td_ucred);
1003 sigio->sio_myref = sigiop;
1005 sx_slock(&proctree_lock);
1014 * Policy - Don't allow a process to FSETOWN a process
1015 * in another session.
1017 * Remove this test to allow maximum flexibility or
1018 * restrict FSETOWN to the current process or process
1019 * group for maximum safety.
1022 if (proc->p_session != curthread->td_proc->p_session) {
1028 } else /* if (pgid < 0) */ {
1029 pgrp = pgfind(-pgid);
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.
1044 if (pgrp->pg_session != curthread->td_proc->p_session) {
1055 * Since funsetownlst() is called without the proctree
1056 * locked, we need to check for P_WEXIT.
1057 * XXX: is ESRCH correct?
1059 if ((proc->p_flag & P_WEXIT) != 0) {
1064 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1065 sigio->sio_proc = proc;
1069 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1070 sigio->sio_pgrp = pgrp;
1073 sx_sunlock(&proctree_lock);
1080 sx_sunlock(&proctree_lock);
1081 crfree(sigio->sio_ucred);
1082 free(sigio, M_SIGIO);
1087 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1091 struct sigio **sigiop;
1096 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1102 * Close a file descriptor.
1104 #ifndef _SYS_SYSPROTO_H_
1113 struct close_args *uap;
1116 return (kern_close(td, uap->fd));
1124 struct filedesc *fdp;
1131 fdp = td->td_proc->p_fd;
1133 AUDIT_SYSCLOSE(td, fd);
1135 FILEDESC_XLOCK(fdp);
1136 if ((unsigned)fd >= fdp->fd_nfiles ||
1137 (fp = fdp->fd_ofiles[fd]) == NULL) {
1138 FILEDESC_XUNLOCK(fdp);
1141 fdp->fd_ofiles[fd] = NULL;
1142 fdp->fd_ofileflags[fd] = 0;
1144 if (td->td_proc->p_fdtol != NULL) {
1146 * Ask fdfree() to sleep to ensure that all relevant
1147 * process leaders can be traversed in closef().
1149 fdp->fd_holdleaderscount++;
1154 * We now hold the fp reference that used to be owned by the
1155 * descriptor array. We have to unlock the FILEDESC *AFTER*
1156 * knote_fdclose to prevent a race of the fd getting opened, a knote
1157 * added, and deleteing a knote for the new fd.
1159 knote_fdclose(td, fd);
1160 if (fp->f_type == DTYPE_MQUEUE)
1161 mq_fdclose(td, fd, fp);
1162 FILEDESC_XUNLOCK(fdp);
1164 error = closef(fp, td);
1166 FILEDESC_XLOCK(fdp);
1167 fdp->fd_holdleaderscount--;
1168 if (fdp->fd_holdleaderscount == 0 &&
1169 fdp->fd_holdleaderswakeup != 0) {
1170 fdp->fd_holdleaderswakeup = 0;
1171 wakeup(&fdp->fd_holdleaderscount);
1173 FILEDESC_XUNLOCK(fdp);
1179 * Close open file descriptors.
1181 #ifndef _SYS_SYSPROTO_H_
1182 struct closefrom_args {
1188 closefrom(struct thread *td, struct closefrom_args *uap)
1190 struct filedesc *fdp;
1193 fdp = td->td_proc->p_fd;
1194 AUDIT_ARG_FD(uap->lowfd);
1197 * Treat negative starting file descriptor values identical to
1198 * closefrom(0) which closes all files.
1202 FILEDESC_SLOCK(fdp);
1203 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1204 if (fdp->fd_ofiles[fd] != NULL) {
1205 FILEDESC_SUNLOCK(fdp);
1206 (void)kern_close(td, fd);
1207 FILEDESC_SLOCK(fdp);
1210 FILEDESC_SUNLOCK(fdp);
1214 #if defined(COMPAT_43)
1216 * Return status information about a file descriptor.
1218 #ifndef _SYS_SYSPROTO_H_
1219 struct ofstat_args {
1226 ofstat(struct thread *td, struct ofstat_args *uap)
1232 error = kern_fstat(td, uap->fd, &ub);
1235 error = copyout(&oub, uap->sb, sizeof(oub));
1239 #endif /* COMPAT_43 */
1242 * Return status information about a file descriptor.
1244 #ifndef _SYS_SYSPROTO_H_
1252 fstat(struct thread *td, struct fstat_args *uap)
1257 error = kern_fstat(td, uap->fd, &ub);
1259 error = copyout(&ub, uap->sb, sizeof(ub));
1264 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1271 if ((error = fget(td, fd, &fp)) != 0)
1274 AUDIT_ARG_FILE(td->td_proc, fp);
1276 error = fo_stat(fp, sbp, td->td_ucred, td);
1279 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1286 * Return status information about a file descriptor.
1288 #ifndef _SYS_SYSPROTO_H_
1289 struct nfstat_args {
1296 nfstat(struct thread *td, struct nfstat_args *uap)
1302 error = kern_fstat(td, uap->fd, &ub);
1304 cvtnstat(&ub, &nub);
1305 error = copyout(&nub, uap->sb, sizeof(nub));
1311 * Return pathconf information about a file descriptor.
1313 #ifndef _SYS_SYSPROTO_H_
1314 struct fpathconf_args {
1321 fpathconf(struct thread *td, struct fpathconf_args *uap)
1327 if ((error = fget(td, uap->fd, &fp)) != 0)
1330 /* If asynchronous I/O is available, it works for all descriptors. */
1331 if (uap->name == _PC_ASYNC_IO) {
1332 td->td_retval[0] = async_io_version;
1338 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1339 vn_lock(vp, LK_SHARED | LK_RETRY);
1340 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1342 VFS_UNLOCK_GIANT(vfslocked);
1343 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1344 if (uap->name != _PC_PIPE_BUF) {
1347 td->td_retval[0] = PIPE_BUF;
1359 * Grow the file table to accomodate (at least) nfd descriptors. This may
1360 * block and drop the filedesc lock, but it will reacquire it before
1364 fdgrowtable(struct filedesc *fdp, int nfd)
1366 struct filedesc0 *fdp0;
1367 struct freetable *fo;
1368 struct file **ntable;
1369 struct file **otable;
1371 int nnfiles, onfiles;
1374 FILEDESC_XLOCK_ASSERT(fdp);
1376 KASSERT(fdp->fd_nfiles > 0,
1377 ("zero-length file table"));
1379 /* compute the size of the new table */
1380 onfiles = fdp->fd_nfiles;
1381 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1382 if (nnfiles <= onfiles)
1383 /* the table is already large enough */
1386 /* allocate a new table and (if required) new bitmaps */
1387 FILEDESC_XUNLOCK(fdp);
1388 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1389 M_FILEDESC, M_ZERO | M_WAITOK);
1390 nfileflags = (char *)&ntable[nnfiles];
1391 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1392 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1393 M_FILEDESC, M_ZERO | M_WAITOK);
1396 FILEDESC_XLOCK(fdp);
1399 * We now have new tables ready to go. Since we dropped the
1400 * filedesc lock to call malloc(), watch out for a race.
1402 onfiles = fdp->fd_nfiles;
1403 if (onfiles >= nnfiles) {
1404 /* we lost the race, but that's OK */
1405 free(ntable, M_FILEDESC);
1407 free(nmap, M_FILEDESC);
1410 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1411 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1412 otable = fdp->fd_ofiles;
1413 fdp->fd_ofileflags = nfileflags;
1414 fdp->fd_ofiles = ntable;
1416 * We must preserve ofiles until the process exits because we can't
1417 * be certain that no threads have references to the old table via
1420 if (onfiles > NDFILE) {
1421 fo = (struct freetable *)&otable[onfiles];
1422 fdp0 = (struct filedesc0 *)fdp;
1423 fo->ft_table = otable;
1424 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1426 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1427 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1428 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1429 free(fdp->fd_map, M_FILEDESC);
1432 fdp->fd_nfiles = nnfiles;
1436 * Allocate a file descriptor for the process.
1439 fdalloc(struct thread *td, int minfd, int *result)
1441 struct proc *p = td->td_proc;
1442 struct filedesc *fdp = p->p_fd;
1445 FILEDESC_XLOCK_ASSERT(fdp);
1447 if (fdp->fd_freefile > minfd)
1448 minfd = fdp->fd_freefile;
1451 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1455 * Search the bitmap for a free descriptor. If none is found, try
1456 * to grow the file table. Keep at it until we either get a file
1457 * descriptor or run into process or system limits; fdgrowtable()
1458 * may drop the filedesc lock, so we're in a race.
1461 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1464 if (fd < fdp->fd_nfiles)
1466 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1470 * Perform some sanity checks, then mark the file descriptor as
1471 * used and return it to the caller.
1473 KASSERT(!fdisused(fdp, fd),
1474 ("fd_first_free() returned non-free descriptor"));
1475 KASSERT(fdp->fd_ofiles[fd] == NULL,
1476 ("free descriptor isn't"));
1477 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1484 * Check to see whether n user file descriptors are available to the process
1488 fdavail(struct thread *td, int n)
1490 struct proc *p = td->td_proc;
1491 struct filedesc *fdp = td->td_proc->p_fd;
1495 FILEDESC_LOCK_ASSERT(fdp);
1498 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1500 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1502 last = min(fdp->fd_nfiles, lim);
1503 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1504 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1505 if (*fpp == NULL && --n <= 0)
1512 * Create a new open file structure and allocate a file decriptor for the
1513 * process that refers to it. We add one reference to the file for the
1514 * descriptor table and one reference for resultfp. This is to prevent us
1515 * being preempted and the entry in the descriptor table closed after we
1516 * release the FILEDESC lock.
1519 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1521 struct proc *p = td->td_proc;
1524 int maxuserfiles = maxfiles - (maxfiles / 20);
1525 static struct timeval lastfail;
1528 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1529 if ((openfiles >= maxuserfiles &&
1530 priv_check(td, PRIV_MAXFILES) != 0) ||
1531 openfiles >= maxfiles) {
1532 if (ppsratecheck(&lastfail, &curfail, 1)) {
1533 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1534 td->td_ucred->cr_ruid);
1536 uma_zfree(file_zone, fp);
1539 atomic_add_int(&openfiles, 1);
1542 * If the process has file descriptor zero open, add the new file
1543 * descriptor to the list of open files at that point, otherwise
1544 * put it at the front of the list of open files.
1546 refcount_init(&fp->f_count, 1);
1549 fp->f_cred = crhold(td->td_ucred);
1550 fp->f_ops = &badfileops;
1553 FILEDESC_XLOCK(p->p_fd);
1554 if ((error = fdalloc(td, 0, &i))) {
1555 FILEDESC_XUNLOCK(p->p_fd);
1561 p->p_fd->fd_ofiles[i] = fp;
1562 if ((flags & O_CLOEXEC) != 0)
1563 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1564 FILEDESC_XUNLOCK(p->p_fd);
1573 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1576 return (fallocf(td, resultfp, resultfd, 0));
1580 * Build a new filedesc structure from another.
1581 * Copy the current, root, and jail root vnode references.
1584 fdinit(struct filedesc *fdp)
1586 struct filedesc0 *newfdp;
1588 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1589 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1591 FILEDESC_XLOCK(fdp);
1592 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1593 if (newfdp->fd_fd.fd_cdir)
1594 VREF(newfdp->fd_fd.fd_cdir);
1595 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1596 if (newfdp->fd_fd.fd_rdir)
1597 VREF(newfdp->fd_fd.fd_rdir);
1598 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1599 if (newfdp->fd_fd.fd_jdir)
1600 VREF(newfdp->fd_fd.fd_jdir);
1601 FILEDESC_XUNLOCK(fdp);
1604 /* Create the file descriptor table. */
1605 newfdp->fd_fd.fd_refcnt = 1;
1606 newfdp->fd_fd.fd_holdcnt = 1;
1607 newfdp->fd_fd.fd_cmask = CMASK;
1608 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1609 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1610 newfdp->fd_fd.fd_nfiles = NDFILE;
1611 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1612 newfdp->fd_fd.fd_lastfile = -1;
1613 return (&newfdp->fd_fd);
1616 static struct filedesc *
1617 fdhold(struct proc *p)
1619 struct filedesc *fdp;
1621 mtx_lock(&fdesc_mtx);
1625 mtx_unlock(&fdesc_mtx);
1630 fddrop(struct filedesc *fdp)
1632 struct filedesc0 *fdp0;
1633 struct freetable *ft;
1636 mtx_lock(&fdesc_mtx);
1637 i = --fdp->fd_holdcnt;
1638 mtx_unlock(&fdesc_mtx);
1642 FILEDESC_LOCK_DESTROY(fdp);
1643 fdp0 = (struct filedesc0 *)fdp;
1644 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1645 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1646 free(ft->ft_table, M_FILEDESC);
1648 free(fdp, M_FILEDESC);
1652 * Share a filedesc structure.
1655 fdshare(struct filedesc *fdp)
1658 FILEDESC_XLOCK(fdp);
1660 FILEDESC_XUNLOCK(fdp);
1665 * Unshare a filedesc structure, if necessary by making a copy
1668 fdunshare(struct proc *p, struct thread *td)
1671 FILEDESC_XLOCK(p->p_fd);
1672 if (p->p_fd->fd_refcnt > 1) {
1673 struct filedesc *tmp;
1675 FILEDESC_XUNLOCK(p->p_fd);
1676 tmp = fdcopy(p->p_fd);
1680 FILEDESC_XUNLOCK(p->p_fd);
1684 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1685 * this is to ease callers, not catch errors.
1688 fdcopy(struct filedesc *fdp)
1690 struct filedesc *newfdp;
1693 /* Certain daemons might not have file descriptors. */
1697 newfdp = fdinit(fdp);
1698 FILEDESC_SLOCK(fdp);
1699 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1700 FILEDESC_SUNLOCK(fdp);
1701 FILEDESC_XLOCK(newfdp);
1702 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1703 FILEDESC_XUNLOCK(newfdp);
1704 FILEDESC_SLOCK(fdp);
1706 /* copy everything except kqueue descriptors */
1707 newfdp->fd_freefile = -1;
1708 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1709 if (fdisused(fdp, i) &&
1710 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1711 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1712 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1713 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1714 fhold(newfdp->fd_ofiles[i]);
1715 newfdp->fd_lastfile = i;
1717 if (newfdp->fd_freefile == -1)
1718 newfdp->fd_freefile = i;
1721 newfdp->fd_cmask = fdp->fd_cmask;
1722 FILEDESC_SUNLOCK(fdp);
1723 FILEDESC_XLOCK(newfdp);
1724 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1725 if (newfdp->fd_ofiles[i] != NULL)
1727 if (newfdp->fd_freefile == -1)
1728 newfdp->fd_freefile = i;
1729 FILEDESC_XUNLOCK(newfdp);
1734 * Release a filedesc structure.
1737 fdfree(struct thread *td)
1739 struct filedesc *fdp;
1742 struct filedesc_to_leader *fdtol;
1744 struct vnode *cdir, *jdir, *rdir, *vp;
1747 /* Certain daemons might not have file descriptors. */
1748 fdp = td->td_proc->p_fd;
1752 /* Check for special need to clear POSIX style locks */
1753 fdtol = td->td_proc->p_fdtol;
1754 if (fdtol != NULL) {
1755 FILEDESC_XLOCK(fdp);
1756 KASSERT(fdtol->fdl_refcount > 0,
1757 ("filedesc_to_refcount botch: fdl_refcount=%d",
1758 fdtol->fdl_refcount));
1759 if (fdtol->fdl_refcount == 1 &&
1760 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1761 for (i = 0, fpp = fdp->fd_ofiles;
1762 i <= fdp->fd_lastfile;
1765 (*fpp)->f_type != DTYPE_VNODE)
1769 FILEDESC_XUNLOCK(fdp);
1770 lf.l_whence = SEEK_SET;
1773 lf.l_type = F_UNLCK;
1775 locked = VFS_LOCK_GIANT(vp->v_mount);
1776 (void) VOP_ADVLOCK(vp,
1777 (caddr_t)td->td_proc->
1782 VFS_UNLOCK_GIANT(locked);
1783 FILEDESC_XLOCK(fdp);
1785 fpp = fdp->fd_ofiles + i;
1789 if (fdtol->fdl_refcount == 1) {
1790 if (fdp->fd_holdleaderscount > 0 &&
1791 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1793 * close() or do_dup() has cleared a reference
1794 * in a shared file descriptor table.
1796 fdp->fd_holdleaderswakeup = 1;
1797 sx_sleep(&fdp->fd_holdleaderscount,
1798 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1801 if (fdtol->fdl_holdcount > 0) {
1803 * Ensure that fdtol->fdl_leader remains
1804 * valid in closef().
1806 fdtol->fdl_wakeup = 1;
1807 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1812 fdtol->fdl_refcount--;
1813 if (fdtol->fdl_refcount == 0 &&
1814 fdtol->fdl_holdcount == 0) {
1815 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1816 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1819 td->td_proc->p_fdtol = NULL;
1820 FILEDESC_XUNLOCK(fdp);
1822 free(fdtol, M_FILEDESC_TO_LEADER);
1824 FILEDESC_XLOCK(fdp);
1825 i = --fdp->fd_refcnt;
1826 FILEDESC_XUNLOCK(fdp);
1830 fpp = fdp->fd_ofiles;
1831 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1833 FILEDESC_XLOCK(fdp);
1836 FILEDESC_XUNLOCK(fdp);
1837 (void) closef(fp, td);
1840 FILEDESC_XLOCK(fdp);
1842 /* XXX This should happen earlier. */
1843 mtx_lock(&fdesc_mtx);
1844 td->td_proc->p_fd = NULL;
1845 mtx_unlock(&fdesc_mtx);
1847 if (fdp->fd_nfiles > NDFILE)
1848 free(fdp->fd_ofiles, M_FILEDESC);
1849 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1850 free(fdp->fd_map, M_FILEDESC);
1854 cdir = fdp->fd_cdir;
1855 fdp->fd_cdir = NULL;
1856 rdir = fdp->fd_rdir;
1857 fdp->fd_rdir = NULL;
1858 jdir = fdp->fd_jdir;
1859 fdp->fd_jdir = NULL;
1860 FILEDESC_XUNLOCK(fdp);
1863 locked = VFS_LOCK_GIANT(cdir->v_mount);
1865 VFS_UNLOCK_GIANT(locked);
1868 locked = VFS_LOCK_GIANT(rdir->v_mount);
1870 VFS_UNLOCK_GIANT(locked);
1873 locked = VFS_LOCK_GIANT(jdir->v_mount);
1875 VFS_UNLOCK_GIANT(locked);
1882 * For setugid programs, we don't want to people to use that setugidness
1883 * to generate error messages which write to a file which otherwise would
1884 * otherwise be off-limits to the process. We check for filesystems where
1885 * the vnode can change out from under us after execve (like [lin]procfs).
1887 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1888 * sufficient. We also don't check for setugidness since we know we are.
1891 is_unsafe(struct file *fp)
1893 if (fp->f_type == DTYPE_VNODE) {
1894 struct vnode *vp = fp->f_vnode;
1896 if ((vp->v_vflag & VV_PROCDEP) != 0)
1903 * Make this setguid thing safe, if at all possible.
1906 setugidsafety(struct thread *td)
1908 struct filedesc *fdp;
1911 /* Certain daemons might not have file descriptors. */
1912 fdp = td->td_proc->p_fd;
1917 * Note: fdp->fd_ofiles may be reallocated out from under us while
1918 * we are blocked in a close. Be careful!
1920 FILEDESC_XLOCK(fdp);
1921 for (i = 0; i <= fdp->fd_lastfile; i++) {
1924 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1927 knote_fdclose(td, i);
1929 * NULL-out descriptor prior to close to avoid
1930 * a race while close blocks.
1932 fp = fdp->fd_ofiles[i];
1933 fdp->fd_ofiles[i] = NULL;
1934 fdp->fd_ofileflags[i] = 0;
1936 FILEDESC_XUNLOCK(fdp);
1937 (void) closef(fp, td);
1938 FILEDESC_XLOCK(fdp);
1941 FILEDESC_XUNLOCK(fdp);
1945 * If a specific file object occupies a specific file descriptor, close the
1946 * file descriptor entry and drop a reference on the file object. This is a
1947 * convenience function to handle a subsequent error in a function that calls
1948 * falloc() that handles the race that another thread might have closed the
1949 * file descriptor out from under the thread creating the file object.
1952 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1955 FILEDESC_XLOCK(fdp);
1956 if (fdp->fd_ofiles[idx] == fp) {
1957 fdp->fd_ofiles[idx] = NULL;
1959 FILEDESC_XUNLOCK(fdp);
1962 FILEDESC_XUNLOCK(fdp);
1966 * Close any files on exec?
1969 fdcloseexec(struct thread *td)
1971 struct filedesc *fdp;
1974 /* Certain daemons might not have file descriptors. */
1975 fdp = td->td_proc->p_fd;
1979 FILEDESC_XLOCK(fdp);
1982 * We cannot cache fd_ofiles or fd_ofileflags since operations
1983 * may block and rip them out from under us.
1985 for (i = 0; i <= fdp->fd_lastfile; i++) {
1986 if (fdp->fd_ofiles[i] != NULL &&
1987 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1988 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1991 knote_fdclose(td, i);
1993 * NULL-out descriptor prior to close to avoid
1994 * a race while close blocks.
1996 fp = fdp->fd_ofiles[i];
1997 fdp->fd_ofiles[i] = NULL;
1998 fdp->fd_ofileflags[i] = 0;
2000 if (fp->f_type == DTYPE_MQUEUE)
2001 mq_fdclose(td, i, fp);
2002 FILEDESC_XUNLOCK(fdp);
2003 (void) closef(fp, td);
2004 FILEDESC_XLOCK(fdp);
2007 FILEDESC_XUNLOCK(fdp);
2011 * It is unsafe for set[ug]id processes to be started with file
2012 * descriptors 0..2 closed, as these descriptors are given implicit
2013 * significance in the Standard C library. fdcheckstd() will create a
2014 * descriptor referencing /dev/null for each of stdin, stdout, and
2015 * stderr that is not already open.
2018 fdcheckstd(struct thread *td)
2020 struct filedesc *fdp;
2021 register_t retval, save;
2022 int i, error, devnull;
2024 fdp = td->td_proc->p_fd;
2027 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2030 for (i = 0; i < 3; i++) {
2031 if (fdp->fd_ofiles[i] != NULL)
2034 save = td->td_retval[0];
2035 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2037 devnull = td->td_retval[0];
2038 td->td_retval[0] = save;
2041 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2043 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2052 * Internal form of close. Decrement reference count on file structure.
2053 * Note: td may be NULL when closing a file that was being passed in a
2056 * XXXRW: Giant is not required for the caller, but often will be held; this
2057 * makes it moderately likely the Giant will be recursed in the VFS case.
2060 closef(struct file *fp, struct thread *td)
2064 struct filedesc_to_leader *fdtol;
2065 struct filedesc *fdp;
2068 * POSIX record locking dictates that any close releases ALL
2069 * locks owned by this process. This is handled by setting
2070 * a flag in the unlock to free ONLY locks obeying POSIX
2071 * semantics, and not to free BSD-style file locks.
2072 * If the descriptor was in a message, POSIX-style locks
2073 * aren't passed with the descriptor, and the thread pointer
2074 * will be NULL. Callers should be careful only to pass a
2075 * NULL thread pointer when there really is no owning
2076 * context that might have locks, or the locks will be
2079 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2083 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2084 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2085 lf.l_whence = SEEK_SET;
2088 lf.l_type = F_UNLCK;
2089 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2090 F_UNLCK, &lf, F_POSIX);
2092 fdtol = td->td_proc->p_fdtol;
2093 if (fdtol != NULL) {
2095 * Handle special case where file descriptor table is
2096 * shared between multiple process leaders.
2098 fdp = td->td_proc->p_fd;
2099 FILEDESC_XLOCK(fdp);
2100 for (fdtol = fdtol->fdl_next;
2101 fdtol != td->td_proc->p_fdtol;
2102 fdtol = fdtol->fdl_next) {
2103 if ((fdtol->fdl_leader->p_flag &
2106 fdtol->fdl_holdcount++;
2107 FILEDESC_XUNLOCK(fdp);
2108 lf.l_whence = SEEK_SET;
2111 lf.l_type = F_UNLCK;
2113 (void) VOP_ADVLOCK(vp,
2114 (caddr_t)fdtol->fdl_leader,
2115 F_UNLCK, &lf, F_POSIX);
2116 FILEDESC_XLOCK(fdp);
2117 fdtol->fdl_holdcount--;
2118 if (fdtol->fdl_holdcount == 0 &&
2119 fdtol->fdl_wakeup != 0) {
2120 fdtol->fdl_wakeup = 0;
2124 FILEDESC_XUNLOCK(fdp);
2126 VFS_UNLOCK_GIANT(vfslocked);
2128 return (fdrop(fp, td));
2132 * Initialize the file pointer with the specified properties.
2134 * The ops are set with release semantics to be certain that the flags, type,
2135 * and data are visible when ops is. This is to prevent ops methods from being
2136 * called with bad data.
2139 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2144 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2148 fget_unlocked(struct filedesc *fdp, int fd)
2153 if (fd < 0 || fd >= fdp->fd_nfiles)
2156 * Fetch the descriptor locklessly. We avoid fdrop() races by
2157 * never raising a refcount above 0. To accomplish this we have
2158 * to use a cmpset loop rather than an atomic_add. The descriptor
2159 * must be re-verified once we acquire a reference to be certain
2160 * that the identity is still correct and we did not lose a race
2161 * due to preemption.
2164 fp = fdp->fd_ofiles[fd];
2167 count = fp->f_count;
2171 * Use an acquire barrier to prevent caching of fd_ofiles
2172 * so it is refreshed for verification.
2174 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2176 if (fp == fdp->fd_ofiles[fd])
2178 fdrop(fp, curthread);
2185 * Extract the file pointer associated with the specified descriptor for the
2186 * current user process.
2188 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2191 * If an error occured the non-zero error is returned and *fpp is set to
2192 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2193 * responsible for fdrop().
2196 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2198 struct filedesc *fdp;
2202 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2204 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2206 if (fp->f_ops == &badfileops) {
2211 * FREAD and FWRITE failure return EBADF as per POSIX.
2213 * Only one flag, or 0, may be specified.
2215 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2216 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2225 fget(struct thread *td, int fd, struct file **fpp)
2228 return(_fget(td, fd, fpp, 0));
2232 fget_read(struct thread *td, int fd, struct file **fpp)
2235 return(_fget(td, fd, fpp, FREAD));
2239 fget_write(struct thread *td, int fd, struct file **fpp)
2242 return(_fget(td, fd, fpp, FWRITE));
2246 * Like fget() but loads the underlying vnode, or returns an error if the
2247 * descriptor does not represent a vnode. Note that pipes use vnodes but
2248 * never have VM objects. The returned vnode will be vref()'d.
2250 * XXX: what about the unused flags ?
2253 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2259 if ((error = _fget(td, fd, &fp, flags)) != 0)
2261 if (fp->f_vnode == NULL) {
2273 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2276 return (_fgetvp(td, fd, vpp, 0));
2280 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2283 return (_fgetvp(td, fd, vpp, FREAD));
2288 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2291 return (_fgetvp(td, fd, vpp, FWRITE));
2296 * Like fget() but loads the underlying socket, or returns an error if the
2297 * descriptor does not represent a socket.
2299 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2302 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2303 * on their file descriptor reference to prevent the socket from being free'd
2307 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2315 if ((error = _fget(td, fd, &fp, 0)) != 0)
2317 if (fp->f_type != DTYPE_SOCKET) {
2322 *fflagp = fp->f_flag;
2333 * Drop the reference count on the socket and XXX release the SX lock in the
2334 * future. The last reference closes the socket.
2336 * Note: fputsock() is deprecated, see comment for fgetsock().
2339 fputsock(struct socket *so)
2344 CURVNET_SET(so->so_vnet);
2350 * Handle the last reference to a file being closed.
2353 _fdrop(struct file *fp, struct thread *td)
2358 if (fp->f_count != 0)
2359 panic("fdrop: count %d", fp->f_count);
2360 if (fp->f_ops != &badfileops)
2361 error = fo_close(fp, td);
2362 atomic_subtract_int(&openfiles, 1);
2364 uma_zfree(file_zone, fp);
2370 * Apply an advisory lock on a file descriptor.
2372 * Just attempt to get a record lock of the requested type on the entire file
2373 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2375 #ifndef _SYS_SYSPROTO_H_
2383 flock(struct thread *td, struct flock_args *uap)
2391 if ((error = fget(td, uap->fd, &fp)) != 0)
2393 if (fp->f_type != DTYPE_VNODE) {
2395 return (EOPNOTSUPP);
2399 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2400 lf.l_whence = SEEK_SET;
2403 if (uap->how & LOCK_UN) {
2404 lf.l_type = F_UNLCK;
2405 atomic_clear_int(&fp->f_flag, FHASLOCK);
2406 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2409 if (uap->how & LOCK_EX)
2410 lf.l_type = F_WRLCK;
2411 else if (uap->how & LOCK_SH)
2412 lf.l_type = F_RDLCK;
2417 atomic_set_int(&fp->f_flag, FHASLOCK);
2418 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2419 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2422 VFS_UNLOCK_GIANT(vfslocked);
2426 * Duplicate the specified descriptor to a free descriptor.
2429 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2435 * If the to-be-dup'd fd number is greater than the allowed number
2436 * of file descriptors, or the fd to be dup'd has already been
2437 * closed, then reject.
2439 FILEDESC_XLOCK(fdp);
2440 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2441 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2442 FILEDESC_XUNLOCK(fdp);
2447 * There are two cases of interest here.
2449 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2451 * For ENXIO steal away the file structure from (dfd) and store it in
2452 * (indx). (dfd) is effectively closed by this operation.
2454 * Any other error code is just returned.
2459 * Check that the mode the file is being opened for is a
2460 * subset of the mode of the existing descriptor.
2462 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2463 FILEDESC_XUNLOCK(fdp);
2466 fp = fdp->fd_ofiles[indx];
2467 fdp->fd_ofiles[indx] = wfp;
2468 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2472 FILEDESC_XUNLOCK(fdp);
2475 * We now own the reference to fp that the ofiles[]
2476 * array used to own. Release it.
2483 * Steal away the file pointer from dfd and stuff it into indx.
2485 fp = fdp->fd_ofiles[indx];
2486 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2487 fdp->fd_ofiles[dfd] = NULL;
2488 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2489 fdp->fd_ofileflags[dfd] = 0;
2493 FILEDESC_XUNLOCK(fdp);
2496 * We now own the reference to fp that the ofiles[] array
2497 * used to own. Release it.
2504 FILEDESC_XUNLOCK(fdp);
2511 * Scan all active processes and prisons to see if any of them have a current
2512 * or root directory of `olddp'. If so, replace them with the new mount point.
2515 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2517 struct filedesc *fdp;
2522 if (vrefcnt(olddp) == 1)
2525 sx_slock(&allproc_lock);
2526 FOREACH_PROC_IN_SYSTEM(p) {
2530 FILEDESC_XLOCK(fdp);
2531 if (fdp->fd_cdir == olddp) {
2533 fdp->fd_cdir = newdp;
2536 if (fdp->fd_rdir == olddp) {
2538 fdp->fd_rdir = newdp;
2541 if (fdp->fd_jdir == olddp) {
2543 fdp->fd_jdir = newdp;
2546 FILEDESC_XUNLOCK(fdp);
2549 sx_sunlock(&allproc_lock);
2550 if (rootvnode == olddp) {
2555 mtx_lock(&prison0.pr_mtx);
2556 if (prison0.pr_root == olddp) {
2558 prison0.pr_root = newdp;
2561 mtx_unlock(&prison0.pr_mtx);
2562 sx_slock(&allprison_lock);
2563 TAILQ_FOREACH(pr, &allprison, pr_list) {
2564 mtx_lock(&pr->pr_mtx);
2565 if (pr->pr_root == olddp) {
2567 pr->pr_root = newdp;
2570 mtx_unlock(&pr->pr_mtx);
2572 sx_sunlock(&allprison_lock);
2577 struct filedesc_to_leader *
2578 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2580 struct filedesc_to_leader *fdtol;
2582 fdtol = malloc(sizeof(struct filedesc_to_leader),
2583 M_FILEDESC_TO_LEADER,
2585 fdtol->fdl_refcount = 1;
2586 fdtol->fdl_holdcount = 0;
2587 fdtol->fdl_wakeup = 0;
2588 fdtol->fdl_leader = leader;
2590 FILEDESC_XLOCK(fdp);
2591 fdtol->fdl_next = old->fdl_next;
2592 fdtol->fdl_prev = old;
2593 old->fdl_next = fdtol;
2594 fdtol->fdl_next->fdl_prev = fdtol;
2595 FILEDESC_XUNLOCK(fdp);
2597 fdtol->fdl_next = fdtol;
2598 fdtol->fdl_prev = fdtol;
2604 * Get file structures globally.
2607 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2610 struct filedesc *fdp;
2615 error = sysctl_wire_old_buffer(req, 0);
2618 if (req->oldptr == NULL) {
2620 sx_slock(&allproc_lock);
2621 FOREACH_PROC_IN_SYSTEM(p) {
2622 if (p->p_state == PRS_NEW)
2627 /* overestimates sparse tables. */
2628 if (fdp->fd_lastfile > 0)
2629 n += fdp->fd_lastfile;
2632 sx_sunlock(&allproc_lock);
2633 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2636 bzero(&xf, sizeof(xf));
2637 xf.xf_size = sizeof(xf);
2638 sx_slock(&allproc_lock);
2639 FOREACH_PROC_IN_SYSTEM(p) {
2641 if (p->p_state == PRS_NEW) {
2645 if (p_cansee(req->td, p) != 0) {
2649 xf.xf_pid = p->p_pid;
2650 xf.xf_uid = p->p_ucred->cr_uid;
2655 FILEDESC_SLOCK(fdp);
2656 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2657 if ((fp = fdp->fd_ofiles[n]) == NULL)
2661 xf.xf_data = fp->f_data;
2662 xf.xf_vnode = fp->f_vnode;
2663 xf.xf_type = fp->f_type;
2664 xf.xf_count = fp->f_count;
2666 xf.xf_offset = fp->f_offset;
2667 xf.xf_flag = fp->f_flag;
2668 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2672 FILEDESC_SUNLOCK(fdp);
2677 sx_sunlock(&allproc_lock);
2681 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2682 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2684 #ifdef KINFO_OFILE_SIZE
2685 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2688 #ifdef COMPAT_FREEBSD7
2690 export_vnode_for_osysctl(struct vnode *vp, int type,
2691 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2694 char *fullpath, *freepath;
2697 bzero(kif, sizeof(*kif));
2698 kif->kf_structsize = sizeof(*kif);
2702 kif->kf_type = KF_TYPE_VNODE;
2703 /* This function only handles directories. */
2704 if (vp->v_type != VDIR) {
2708 kif->kf_vnode_type = KF_VTYPE_VDIR;
2711 * This is not a true file descriptor, so we set a bogus refcount
2712 * and offset to indicate these fields should be ignored.
2714 kif->kf_ref_count = -1;
2715 kif->kf_offset = -1;
2719 FILEDESC_SUNLOCK(fdp);
2720 vn_fullpath(curthread, vp, &fullpath, &freepath);
2721 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2723 VFS_UNLOCK_GIANT(vfslocked);
2724 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2725 if (freepath != NULL)
2726 free(freepath, M_TEMP);
2727 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2728 FILEDESC_SLOCK(fdp);
2733 * Get per-process file descriptors for use by procstat(1), et al.
2736 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2738 char *fullpath, *freepath;
2739 struct kinfo_ofile *kif;
2740 struct filedesc *fdp;
2741 int error, i, *name;
2750 if ((p = pfind((pid_t)name[0])) == NULL)
2752 if ((error = p_candebug(curthread, p))) {
2760 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2761 FILEDESC_SLOCK(fdp);
2762 if (fdp->fd_cdir != NULL)
2763 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2765 if (fdp->fd_rdir != NULL)
2766 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2768 if (fdp->fd_jdir != NULL)
2769 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2771 for (i = 0; i < fdp->fd_nfiles; i++) {
2772 if ((fp = fdp->fd_ofiles[i]) == NULL)
2774 bzero(kif, sizeof(*kif));
2775 kif->kf_structsize = sizeof(*kif);
2780 switch (fp->f_type) {
2782 kif->kf_type = KF_TYPE_VNODE;
2787 kif->kf_type = KF_TYPE_SOCKET;
2792 kif->kf_type = KF_TYPE_PIPE;
2796 kif->kf_type = KF_TYPE_FIFO;
2801 kif->kf_type = KF_TYPE_KQUEUE;
2805 kif->kf_type = KF_TYPE_CRYPTO;
2809 kif->kf_type = KF_TYPE_MQUEUE;
2813 kif->kf_type = KF_TYPE_SHM;
2817 kif->kf_type = KF_TYPE_SEM;
2821 kif->kf_type = KF_TYPE_PTS;
2826 kif->kf_type = KF_TYPE_UNKNOWN;
2829 kif->kf_ref_count = fp->f_count;
2830 if (fp->f_flag & FREAD)
2831 kif->kf_flags |= KF_FLAG_READ;
2832 if (fp->f_flag & FWRITE)
2833 kif->kf_flags |= KF_FLAG_WRITE;
2834 if (fp->f_flag & FAPPEND)
2835 kif->kf_flags |= KF_FLAG_APPEND;
2836 if (fp->f_flag & FASYNC)
2837 kif->kf_flags |= KF_FLAG_ASYNC;
2838 if (fp->f_flag & FFSYNC)
2839 kif->kf_flags |= KF_FLAG_FSYNC;
2840 if (fp->f_flag & FNONBLOCK)
2841 kif->kf_flags |= KF_FLAG_NONBLOCK;
2842 if (fp->f_flag & O_DIRECT)
2843 kif->kf_flags |= KF_FLAG_DIRECT;
2844 if (fp->f_flag & FHASLOCK)
2845 kif->kf_flags |= KF_FLAG_HASLOCK;
2846 kif->kf_offset = fp->f_offset;
2849 switch (vp->v_type) {
2851 kif->kf_vnode_type = KF_VTYPE_VNON;
2854 kif->kf_vnode_type = KF_VTYPE_VREG;
2857 kif->kf_vnode_type = KF_VTYPE_VDIR;
2860 kif->kf_vnode_type = KF_VTYPE_VBLK;
2863 kif->kf_vnode_type = KF_VTYPE_VCHR;
2866 kif->kf_vnode_type = KF_VTYPE_VLNK;
2869 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2872 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2875 kif->kf_vnode_type = KF_VTYPE_VBAD;
2878 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2882 * It is OK to drop the filedesc lock here as we will
2883 * re-validate and re-evaluate its properties when
2884 * the loop continues.
2888 FILEDESC_SUNLOCK(fdp);
2889 vn_fullpath(curthread, vp, &fullpath, &freepath);
2890 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2892 VFS_UNLOCK_GIANT(vfslocked);
2893 strlcpy(kif->kf_path, fullpath,
2894 sizeof(kif->kf_path));
2895 if (freepath != NULL)
2896 free(freepath, M_TEMP);
2897 FILEDESC_SLOCK(fdp);
2900 struct sockaddr *sa;
2902 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2903 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2904 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2907 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2908 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2909 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2912 kif->kf_sock_domain =
2913 so->so_proto->pr_domain->dom_family;
2914 kif->kf_sock_type = so->so_type;
2915 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2918 strlcpy(kif->kf_path, tty_devname(tp),
2919 sizeof(kif->kf_path));
2921 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2925 FILEDESC_SUNLOCK(fdp);
2931 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2932 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2933 #endif /* COMPAT_FREEBSD7 */
2935 #ifdef KINFO_FILE_SIZE
2936 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2940 export_vnode_for_sysctl(struct vnode *vp, int type,
2941 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2944 char *fullpath, *freepath;
2947 bzero(kif, sizeof(*kif));
2951 kif->kf_type = KF_TYPE_VNODE;
2952 /* This function only handles directories. */
2953 if (vp->v_type != VDIR) {
2957 kif->kf_vnode_type = KF_VTYPE_VDIR;
2960 * This is not a true file descriptor, so we set a bogus refcount
2961 * and offset to indicate these fields should be ignored.
2963 kif->kf_ref_count = -1;
2964 kif->kf_offset = -1;
2968 FILEDESC_SUNLOCK(fdp);
2969 vn_fullpath(curthread, vp, &fullpath, &freepath);
2970 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2972 VFS_UNLOCK_GIANT(vfslocked);
2973 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2974 if (freepath != NULL)
2975 free(freepath, M_TEMP);
2976 /* Pack record size down */
2977 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2978 strlen(kif->kf_path) + 1;
2979 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2980 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2981 FILEDESC_SLOCK(fdp);
2986 * Get per-process file descriptors for use by procstat(1), et al.
2989 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
2991 char *fullpath, *freepath;
2992 struct kinfo_file *kif;
2993 struct filedesc *fdp;
2994 int error, i, *name;
3004 if ((p = pfind((pid_t)name[0])) == NULL)
3006 if ((error = p_candebug(curthread, p))) {
3014 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3015 FILEDESC_SLOCK(fdp);
3016 if (fdp->fd_cdir != NULL)
3017 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3019 if (fdp->fd_rdir != NULL)
3020 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3022 if (fdp->fd_jdir != NULL)
3023 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3025 for (i = 0; i < fdp->fd_nfiles; i++) {
3026 if ((fp = fdp->fd_ofiles[i]) == NULL)
3028 bzero(kif, sizeof(*kif));
3033 switch (fp->f_type) {
3035 kif->kf_type = KF_TYPE_VNODE;
3040 kif->kf_type = KF_TYPE_SOCKET;
3045 kif->kf_type = KF_TYPE_PIPE;
3049 kif->kf_type = KF_TYPE_FIFO;
3054 kif->kf_type = KF_TYPE_KQUEUE;
3058 kif->kf_type = KF_TYPE_CRYPTO;
3062 kif->kf_type = KF_TYPE_MQUEUE;
3066 kif->kf_type = KF_TYPE_SHM;
3070 kif->kf_type = KF_TYPE_SEM;
3074 kif->kf_type = KF_TYPE_PTS;
3079 kif->kf_type = KF_TYPE_UNKNOWN;
3082 kif->kf_ref_count = fp->f_count;
3083 if (fp->f_flag & FREAD)
3084 kif->kf_flags |= KF_FLAG_READ;
3085 if (fp->f_flag & FWRITE)
3086 kif->kf_flags |= KF_FLAG_WRITE;
3087 if (fp->f_flag & FAPPEND)
3088 kif->kf_flags |= KF_FLAG_APPEND;
3089 if (fp->f_flag & FASYNC)
3090 kif->kf_flags |= KF_FLAG_ASYNC;
3091 if (fp->f_flag & FFSYNC)
3092 kif->kf_flags |= KF_FLAG_FSYNC;
3093 if (fp->f_flag & FNONBLOCK)
3094 kif->kf_flags |= KF_FLAG_NONBLOCK;
3095 if (fp->f_flag & O_DIRECT)
3096 kif->kf_flags |= KF_FLAG_DIRECT;
3097 if (fp->f_flag & FHASLOCK)
3098 kif->kf_flags |= KF_FLAG_HASLOCK;
3099 kif->kf_offset = fp->f_offset;
3102 switch (vp->v_type) {
3104 kif->kf_vnode_type = KF_VTYPE_VNON;
3107 kif->kf_vnode_type = KF_VTYPE_VREG;
3110 kif->kf_vnode_type = KF_VTYPE_VDIR;
3113 kif->kf_vnode_type = KF_VTYPE_VBLK;
3116 kif->kf_vnode_type = KF_VTYPE_VCHR;
3119 kif->kf_vnode_type = KF_VTYPE_VLNK;
3122 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3125 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3128 kif->kf_vnode_type = KF_VTYPE_VBAD;
3131 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3135 * It is OK to drop the filedesc lock here as we will
3136 * re-validate and re-evaluate its properties when
3137 * the loop continues.
3141 FILEDESC_SUNLOCK(fdp);
3142 vn_fullpath(curthread, vp, &fullpath, &freepath);
3143 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3145 VFS_UNLOCK_GIANT(vfslocked);
3146 strlcpy(kif->kf_path, fullpath,
3147 sizeof(kif->kf_path));
3148 if (freepath != NULL)
3149 free(freepath, M_TEMP);
3150 FILEDESC_SLOCK(fdp);
3153 struct sockaddr *sa;
3155 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3156 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3157 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3160 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3161 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3162 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3165 kif->kf_sock_domain =
3166 so->so_proto->pr_domain->dom_family;
3167 kif->kf_sock_type = so->so_type;
3168 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3171 strlcpy(kif->kf_path, tty_devname(tp),
3172 sizeof(kif->kf_path));
3174 /* Pack record size down */
3175 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3176 strlen(kif->kf_path) + 1;
3177 kif->kf_structsize = roundup(kif->kf_structsize,
3179 oldidx = req->oldidx;
3180 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3182 if (error == ENOMEM) {
3184 * The hack to keep the ABI of sysctl
3185 * kern.proc.filedesc intact, but not
3186 * to account a partially copied
3187 * kinfo_file into the oldidx.
3189 req->oldidx = oldidx;
3195 FILEDESC_SUNLOCK(fdp);
3201 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3202 sysctl_kern_proc_filedesc, "Process filedesc entries");
3206 * For the purposes of debugging, generate a human-readable string for the
3210 file_type_to_name(short type)
3240 * For the purposes of debugging, identify a process (if any, perhaps one of
3241 * many) that references the passed file in its file descriptor array. Return
3244 static struct proc *
3245 file_to_first_proc(struct file *fp)
3247 struct filedesc *fdp;
3251 FOREACH_PROC_IN_SYSTEM(p) {
3252 if (p->p_state == PRS_NEW)
3257 for (n = 0; n < fdp->fd_nfiles; n++) {
3258 if (fp == fdp->fd_ofiles[n])
3266 db_print_file(struct file *fp, int header)
3271 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3272 "File", "Type", "Data", "Flag", "GCFl", "Count",
3273 "MCount", "Vnode", "FPID", "FCmd");
3274 p = file_to_first_proc(fp);
3275 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3276 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3277 0, fp->f_count, 0, fp->f_vnode,
3278 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3281 DB_SHOW_COMMAND(file, db_show_file)
3286 db_printf("usage: show file <addr>\n");
3289 fp = (struct file *)addr;
3290 db_print_file(fp, 1);
3293 DB_SHOW_COMMAND(files, db_show_files)
3295 struct filedesc *fdp;
3302 FOREACH_PROC_IN_SYSTEM(p) {
3303 if (p->p_state == PRS_NEW)
3305 if ((fdp = p->p_fd) == NULL)
3307 for (n = 0; n < fdp->fd_nfiles; ++n) {
3308 if ((fp = fdp->fd_ofiles[n]) == NULL)
3310 db_print_file(fp, header);
3317 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3318 &maxfilesperproc, 0, "Maximum files allowed open per process");
3320 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3321 &maxfiles, 0, "Maximum number of files");
3323 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3324 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3328 filelistinit(void *dummy)
3331 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3332 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3333 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3334 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3336 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3338 /*-------------------------------------------------------------------*/
3341 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3348 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3355 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3362 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3369 badfo_kqfilter(struct file *fp, struct knote *kn)
3376 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3383 badfo_close(struct file *fp, struct thread *td)
3389 struct fileops badfileops = {
3390 .fo_read = badfo_readwrite,
3391 .fo_write = badfo_readwrite,
3392 .fo_truncate = badfo_truncate,
3393 .fo_ioctl = badfo_ioctl,
3394 .fo_poll = badfo_poll,
3395 .fo_kqfilter = badfo_kqfilter,
3396 .fo_stat = badfo_stat,
3397 .fo_close = badfo_close,
3401 /*-------------------------------------------------------------------*/
3404 * File Descriptor pseudo-device driver (/dev/fd/).
3406 * Opening minor device N dup()s the file (if any) connected to file
3407 * descriptor N belonging to the calling process. Note that this driver
3408 * consists of only the ``open()'' routine, because all subsequent
3409 * references to this file will be direct to the other driver.
3411 * XXX: we could give this one a cloning event handler if necessary.
3416 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3420 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3421 * the file descriptor being sought for duplication. The error
3422 * return ensures that the vnode for this device will be released
3423 * by vn_open. Open will detect this special error and take the
3424 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3425 * will simply report the error.
3427 td->td_dupfd = dev2unit(dev);
3431 static struct cdevsw fildesc_cdevsw = {
3432 .d_version = D_VERSION,
3438 fildesc_drvinit(void *unused)
3442 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3443 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3444 make_dev_alias(dev, "stdin");
3445 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3446 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3447 make_dev_alias(dev, "stdout");
3448 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3449 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3450 make_dev_alias(dev, "stderr");
3453 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);