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 */
104 static int do_dup(struct thread *td, int flags, int old, int new,
106 static int fd_first_free(struct filedesc *, int, int);
107 static int fd_last_used(struct filedesc *, int, int);
108 static void fdgrowtable(struct filedesc *, int);
109 static void fdunused(struct filedesc *fdp, int fd);
110 static void fdused(struct filedesc *fdp, int fd);
113 * A process is initially started out with NDFILE descriptors stored within
114 * this structure, selected to be enough for typical applications based on
115 * the historical limit of 20 open files (and the usage of descriptors by
116 * shells). If these descriptors are exhausted, a larger descriptor table
117 * may be allocated, up to a process' resource limit; the internal arrays
121 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
122 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
123 #define NDSLOT(x) ((x) / NDENTRIES)
124 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
125 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
128 * Storage required per open file descriptor.
130 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
133 * Storage to hold unused ofiles that need to be reclaimed.
136 struct file **ft_table;
137 SLIST_ENTRY(freetable) ft_next;
141 * Basic allocation of descriptors:
142 * one of the above, plus arrays for NDFILE descriptors.
145 struct filedesc fd_fd;
147 * ofiles which need to be reclaimed on free.
149 SLIST_HEAD(,freetable) fd_free;
151 * These arrays are used when the number of open files is
152 * <= NDFILE, and are then pointed to by the pointers above.
154 struct file *fd_dfiles[NDFILE];
155 char fd_dfileflags[NDFILE];
156 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
160 * Descriptor management.
162 volatile int openfiles; /* actual number of open files */
163 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
164 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
166 /* A mutex to protect the association between a proc and filedesc. */
167 static struct mtx fdesc_mtx;
170 * Find the first zero bit in the given bitmap, starting at low and not
171 * exceeding size - 1.
174 fd_first_free(struct filedesc *fdp, int low, int size)
176 NDSLOTTYPE *map = fdp->fd_map;
184 if (low % NDENTRIES) {
185 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
186 if ((mask &= ~map[off]) != 0UL)
187 return (off * NDENTRIES + ffsl(mask) - 1);
190 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
191 if (map[off] != ~0UL)
192 return (off * NDENTRIES + ffsl(~map[off]) - 1);
197 * Find the highest non-zero bit in the given bitmap, starting at low and
198 * not exceeding size - 1.
201 fd_last_used(struct filedesc *fdp, int low, int size)
203 NDSLOTTYPE *map = fdp->fd_map;
211 if (size % NDENTRIES) {
212 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
213 if ((mask &= map[off]) != 0)
214 return (off * NDENTRIES + flsl(mask) - 1);
217 for (minoff = NDSLOT(low); off >= minoff; --off)
219 return (off * NDENTRIES + flsl(map[off]) - 1);
224 fdisused(struct filedesc *fdp, int fd)
226 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
227 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
228 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
232 * Mark a file descriptor as used.
235 fdused(struct filedesc *fdp, int fd)
238 FILEDESC_XLOCK_ASSERT(fdp);
239 KASSERT(!fdisused(fdp, fd),
240 ("fd already used"));
242 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
243 if (fd > fdp->fd_lastfile)
244 fdp->fd_lastfile = fd;
245 if (fd == fdp->fd_freefile)
246 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
250 * Mark a file descriptor as unused.
253 fdunused(struct filedesc *fdp, int fd)
256 FILEDESC_XLOCK_ASSERT(fdp);
257 KASSERT(fdisused(fdp, fd),
258 ("fd is already unused"));
259 KASSERT(fdp->fd_ofiles[fd] == NULL,
260 ("fd is still in use"));
262 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
263 if (fd < fdp->fd_freefile)
264 fdp->fd_freefile = fd;
265 if (fd == fdp->fd_lastfile)
266 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
270 * System calls on descriptors.
272 #ifndef _SYS_SYSPROTO_H_
273 struct getdtablesize_args {
279 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
281 struct proc *p = td->td_proc;
285 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
291 * Duplicate a file descriptor to a particular value.
293 * Note: keep in mind that a potential race condition exists when closing
294 * descriptors from a shared descriptor table (via rfork).
296 #ifndef _SYS_SYSPROTO_H_
304 dup2(struct thread *td, struct dup2_args *uap)
307 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
312 * Duplicate a file descriptor.
314 #ifndef _SYS_SYSPROTO_H_
321 dup(struct thread *td, struct dup_args *uap)
324 return (do_dup(td, 0, (int)uap->fd, 0, td->td_retval));
328 * The file control system call.
330 #ifndef _SYS_SYSPROTO_H_
339 fcntl(struct thread *td, struct fcntl_args *uap)
354 * Convert old flock structure to new.
356 error = copyin((void *)(intptr_t)uap->arg, &ofl, sizeof(ofl));
357 fl.l_start = ofl.l_start;
358 fl.l_len = ofl.l_len;
359 fl.l_pid = ofl.l_pid;
360 fl.l_type = ofl.l_type;
361 fl.l_whence = ofl.l_whence;
381 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
390 error = kern_fcntl(td, uap->fd, cmd, arg);
393 if (uap->cmd == F_OGETLK) {
394 ofl.l_start = fl.l_start;
395 ofl.l_len = fl.l_len;
396 ofl.l_pid = fl.l_pid;
397 ofl.l_type = fl.l_type;
398 ofl.l_whence = fl.l_whence;
399 error = copyout(&ofl, (void *)(intptr_t)uap->arg, sizeof(ofl));
400 } else if (uap->cmd == F_GETLK) {
401 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
406 static inline struct file *
407 fdtofp(int fd, struct filedesc *fdp)
411 FILEDESC_LOCK_ASSERT(fdp);
412 if ((unsigned)fd >= fdp->fd_nfiles ||
413 (fp = fdp->fd_ofiles[fd]) == NULL)
419 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
421 struct filedesc *fdp;
441 error = do_dup(td, DUP_FCNTL, fd, tmp, td->td_retval);
446 error = do_dup(td, DUP_FIXED, fd, tmp, td->td_retval);
451 if ((fp = fdtofp(fd, fdp)) == NULL) {
452 FILEDESC_SUNLOCK(fdp);
456 pop = &fdp->fd_ofileflags[fd];
457 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
458 FILEDESC_SUNLOCK(fdp);
463 if ((fp = fdtofp(fd, fdp)) == NULL) {
464 FILEDESC_XUNLOCK(fdp);
468 pop = &fdp->fd_ofileflags[fd];
469 *pop = (*pop &~ UF_EXCLOSE) |
470 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
471 FILEDESC_XUNLOCK(fdp);
476 if ((fp = fdtofp(fd, fdp)) == NULL) {
477 FILEDESC_SUNLOCK(fdp);
481 td->td_retval[0] = OFLAGS(fp->f_flag);
482 FILEDESC_SUNLOCK(fdp);
487 if ((fp = fdtofp(fd, fdp)) == NULL) {
488 FILEDESC_SUNLOCK(fdp);
493 FILEDESC_SUNLOCK(fdp);
495 tmp = flg = fp->f_flag;
497 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
498 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
499 tmp = fp->f_flag & FNONBLOCK;
500 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
505 tmp = fp->f_flag & FASYNC;
506 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
511 atomic_clear_int(&fp->f_flag, FNONBLOCK);
513 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
519 if ((fp = fdtofp(fd, fdp)) == NULL) {
520 FILEDESC_SUNLOCK(fdp);
525 FILEDESC_SUNLOCK(fdp);
526 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
528 td->td_retval[0] = tmp;
534 if ((fp = fdtofp(fd, fdp)) == NULL) {
535 FILEDESC_SUNLOCK(fdp);
540 FILEDESC_SUNLOCK(fdp);
542 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
547 error = priv_check(td, PRIV_NFS_LOCKD);
555 /* FALLTHROUGH F_SETLK */
560 if ((fp = fdtofp(fd, fdp)) == NULL) {
561 FILEDESC_SUNLOCK(fdp);
565 if (fp->f_type != DTYPE_VNODE) {
566 FILEDESC_SUNLOCK(fdp);
570 flp = (struct flock *)arg;
571 if (flp->l_whence == SEEK_CUR) {
572 if (fp->f_offset < 0 ||
574 fp->f_offset > OFF_MAX - flp->l_start)) {
575 FILEDESC_SUNLOCK(fdp);
579 flp->l_start += fp->f_offset;
583 * VOP_ADVLOCK() may block.
586 FILEDESC_SUNLOCK(fdp);
588 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
589 switch (flp->l_type) {
591 if ((fp->f_flag & FREAD) == 0) {
595 PROC_LOCK(p->p_leader);
596 p->p_leader->p_flag |= P_ADVLOCK;
597 PROC_UNLOCK(p->p_leader);
598 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
602 if ((fp->f_flag & FWRITE) == 0) {
606 PROC_LOCK(p->p_leader);
607 p->p_leader->p_flag |= P_ADVLOCK;
608 PROC_UNLOCK(p->p_leader);
609 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
613 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
618 * Temporary api for testing remote lock
621 if (flg != F_REMOTE) {
625 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
626 F_UNLCKSYS, flp, flg);
632 VFS_UNLOCK_GIANT(vfslocked);
634 /* Check for race with close */
636 if ((unsigned) fd >= fdp->fd_nfiles ||
637 fp != fdp->fd_ofiles[fd]) {
638 FILEDESC_SUNLOCK(fdp);
639 flp->l_whence = SEEK_SET;
642 flp->l_type = F_UNLCK;
643 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
644 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
645 F_UNLCK, flp, F_POSIX);
646 VFS_UNLOCK_GIANT(vfslocked);
649 FILEDESC_SUNLOCK(fdp);
655 if ((fp = fdtofp(fd, fdp)) == NULL) {
656 FILEDESC_SUNLOCK(fdp);
660 if (fp->f_type != DTYPE_VNODE) {
661 FILEDESC_SUNLOCK(fdp);
665 flp = (struct flock *)arg;
666 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
667 flp->l_type != F_UNLCK) {
668 FILEDESC_SUNLOCK(fdp);
672 if (flp->l_whence == SEEK_CUR) {
673 if ((flp->l_start > 0 &&
674 fp->f_offset > OFF_MAX - flp->l_start) ||
676 fp->f_offset < OFF_MIN - flp->l_start)) {
677 FILEDESC_SUNLOCK(fdp);
681 flp->l_start += fp->f_offset;
684 * VOP_ADVLOCK() may block.
687 FILEDESC_SUNLOCK(fdp);
689 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
690 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
692 VFS_UNLOCK_GIANT(vfslocked);
698 arg = arg ? 128 * 1024: 0;
702 if ((fp = fdtofp(fd, fdp)) == NULL) {
703 FILEDESC_SUNLOCK(fdp);
707 if (fp->f_type != DTYPE_VNODE) {
708 FILEDESC_SUNLOCK(fdp);
713 FILEDESC_SUNLOCK(fdp);
716 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
717 error = vn_lock(vp, LK_SHARED);
719 goto readahead_vnlock_fail;
720 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
722 fp->f_seqcount = (arg + bsize - 1) / bsize;
724 new = old = fp->f_flag;
726 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
727 readahead_vnlock_fail:
728 VFS_UNLOCK_GIANT(vfslocked);
732 new = old = fp->f_flag;
734 } while (!atomic_cmpset_rel_int(&fp->f_flag, old, new));
743 VFS_UNLOCK_GIANT(vfslocked);
748 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
751 do_dup(struct thread *td, int flags, int old, int new,
754 struct filedesc *fdp;
758 int error, holdleaders, maxfd;
764 * Verify we have a valid descriptor to dup from and possibly to
765 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
766 * return EINVAL when the new descriptor is out of bounds.
771 return (flags & DUP_FCNTL ? EINVAL : EBADF);
773 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
776 return (flags & DUP_FCNTL ? EINVAL : EBADF);
779 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
780 FILEDESC_XUNLOCK(fdp);
783 if (flags & DUP_FIXED && old == new) {
785 FILEDESC_XUNLOCK(fdp);
788 fp = fdp->fd_ofiles[old];
792 * If the caller specified a file descriptor, make sure the file
793 * table is large enough to hold it, and grab it. Otherwise, just
794 * allocate a new descriptor the usual way. Since the filedesc
795 * lock may be temporarily dropped in the process, we have to look
798 if (flags & DUP_FIXED) {
799 if (new >= fdp->fd_nfiles)
800 fdgrowtable(fdp, new + 1);
801 if (fdp->fd_ofiles[new] == NULL)
804 if ((error = fdalloc(td, new, &new)) != 0) {
805 FILEDESC_XUNLOCK(fdp);
812 * If the old file changed out from under us then treat it as a
813 * bad file descriptor. Userland should do its own locking to
816 if (fdp->fd_ofiles[old] != fp) {
817 /* we've allocated a descriptor which we won't use */
818 if (fdp->fd_ofiles[new] == NULL)
820 FILEDESC_XUNLOCK(fdp);
825 ("new fd is same as old"));
828 * Save info on the descriptor being overwritten. We cannot close
829 * it without introducing an ownership race for the slot, since we
830 * need to drop the filedesc lock to call closef().
832 * XXX this duplicates parts of close().
834 delfp = fdp->fd_ofiles[new];
837 if (td->td_proc->p_fdtol != NULL) {
839 * Ask fdfree() to sleep to ensure that all relevant
840 * process leaders can be traversed in closef().
842 fdp->fd_holdleaderscount++;
848 * Duplicate the source descriptor
850 fdp->fd_ofiles[new] = fp;
851 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
852 if (new > fdp->fd_lastfile)
853 fdp->fd_lastfile = new;
857 * If we dup'd over a valid file, we now own the reference to it
858 * and must dispose of it using closef() semantics (as if a
859 * close() were performed on it).
861 * XXX this duplicates parts of close().
864 knote_fdclose(td, new);
865 if (delfp->f_type == DTYPE_MQUEUE)
866 mq_fdclose(td, new, delfp);
867 FILEDESC_XUNLOCK(fdp);
868 (void) closef(delfp, td);
871 fdp->fd_holdleaderscount--;
872 if (fdp->fd_holdleaderscount == 0 &&
873 fdp->fd_holdleaderswakeup != 0) {
874 fdp->fd_holdleaderswakeup = 0;
875 wakeup(&fdp->fd_holdleaderscount);
877 FILEDESC_XUNLOCK(fdp);
880 FILEDESC_XUNLOCK(fdp);
886 * If sigio is on the list associated with a process or process group,
887 * disable signalling from the device, remove sigio from the list and
891 funsetown(struct sigio **sigiop)
901 *(sigio->sio_myref) = NULL;
902 if ((sigio)->sio_pgid < 0) {
903 struct pgrp *pg = (sigio)->sio_pgrp;
905 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
909 struct proc *p = (sigio)->sio_proc;
911 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
916 crfree(sigio->sio_ucred);
917 free(sigio, M_SIGIO);
921 * Free a list of sigio structures.
922 * We only need to lock the SIGIO_LOCK because we have made ourselves
923 * inaccessible to callers of fsetown and therefore do not need to lock
924 * the proc or pgrp struct for the list manipulation.
927 funsetownlst(struct sigiolst *sigiolst)
933 sigio = SLIST_FIRST(sigiolst);
940 * Every entry of the list should belong
941 * to a single proc or pgrp.
943 if (sigio->sio_pgid < 0) {
944 pg = sigio->sio_pgrp;
945 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
946 } else /* if (sigio->sio_pgid > 0) */ {
948 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
952 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
953 *(sigio->sio_myref) = NULL;
955 KASSERT(sigio->sio_pgid < 0,
956 ("Proc sigio in pgrp sigio list"));
957 KASSERT(sigio->sio_pgrp == pg,
958 ("Bogus pgrp in sigio list"));
960 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
963 } else /* if (p != NULL) */ {
964 KASSERT(sigio->sio_pgid > 0,
965 ("Pgrp sigio in proc sigio list"));
966 KASSERT(sigio->sio_proc == p,
967 ("Bogus proc in sigio list"));
969 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
974 crfree(sigio->sio_ucred);
975 free(sigio, M_SIGIO);
982 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
984 * After permission checking, add a sigio structure to the sigio list for
985 * the process or process group.
988 fsetown(pid_t pgid, struct sigio **sigiop)
1002 /* Allocate and fill in the new sigio out of locks. */
1003 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1004 sigio->sio_pgid = pgid;
1005 sigio->sio_ucred = crhold(curthread->td_ucred);
1006 sigio->sio_myref = sigiop;
1008 sx_slock(&proctree_lock);
1017 * Policy - Don't allow a process to FSETOWN a process
1018 * in another session.
1020 * Remove this test to allow maximum flexibility or
1021 * restrict FSETOWN to the current process or process
1022 * group for maximum safety.
1025 if (proc->p_session != curthread->td_proc->p_session) {
1031 } else /* if (pgid < 0) */ {
1032 pgrp = pgfind(-pgid);
1040 * Policy - Don't allow a process to FSETOWN a process
1041 * in another session.
1043 * Remove this test to allow maximum flexibility or
1044 * restrict FSETOWN to the current process or process
1045 * group for maximum safety.
1047 if (pgrp->pg_session != curthread->td_proc->p_session) {
1058 * Since funsetownlst() is called without the proctree
1059 * locked, we need to check for P_WEXIT.
1060 * XXX: is ESRCH correct?
1062 if ((proc->p_flag & P_WEXIT) != 0) {
1067 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1068 sigio->sio_proc = proc;
1072 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1073 sigio->sio_pgrp = pgrp;
1076 sx_sunlock(&proctree_lock);
1083 sx_sunlock(&proctree_lock);
1084 crfree(sigio->sio_ucred);
1085 free(sigio, M_SIGIO);
1090 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1094 struct sigio **sigiop;
1099 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1105 * Close a file descriptor.
1107 #ifndef _SYS_SYSPROTO_H_
1116 struct close_args *uap;
1119 return (kern_close(td, uap->fd));
1127 struct filedesc *fdp;
1134 fdp = td->td_proc->p_fd;
1136 AUDIT_SYSCLOSE(td, fd);
1138 FILEDESC_XLOCK(fdp);
1139 if ((unsigned)fd >= fdp->fd_nfiles ||
1140 (fp = fdp->fd_ofiles[fd]) == NULL) {
1141 FILEDESC_XUNLOCK(fdp);
1144 fdp->fd_ofiles[fd] = NULL;
1145 fdp->fd_ofileflags[fd] = 0;
1147 if (td->td_proc->p_fdtol != NULL) {
1149 * Ask fdfree() to sleep to ensure that all relevant
1150 * process leaders can be traversed in closef().
1152 fdp->fd_holdleaderscount++;
1157 * We now hold the fp reference that used to be owned by the
1158 * descriptor array. We have to unlock the FILEDESC *AFTER*
1159 * knote_fdclose to prevent a race of the fd getting opened, a knote
1160 * added, and deleteing a knote for the new fd.
1162 knote_fdclose(td, fd);
1163 if (fp->f_type == DTYPE_MQUEUE)
1164 mq_fdclose(td, fd, fp);
1165 FILEDESC_XUNLOCK(fdp);
1167 error = closef(fp, td);
1169 FILEDESC_XLOCK(fdp);
1170 fdp->fd_holdleaderscount--;
1171 if (fdp->fd_holdleaderscount == 0 &&
1172 fdp->fd_holdleaderswakeup != 0) {
1173 fdp->fd_holdleaderswakeup = 0;
1174 wakeup(&fdp->fd_holdleaderscount);
1176 FILEDESC_XUNLOCK(fdp);
1182 * Close open file descriptors.
1184 #ifndef _SYS_SYSPROTO_H_
1185 struct closefrom_args {
1191 closefrom(struct thread *td, struct closefrom_args *uap)
1193 struct filedesc *fdp;
1196 fdp = td->td_proc->p_fd;
1197 AUDIT_ARG_FD(uap->lowfd);
1200 * Treat negative starting file descriptor values identical to
1201 * closefrom(0) which closes all files.
1205 FILEDESC_SLOCK(fdp);
1206 for (fd = uap->lowfd; fd < fdp->fd_nfiles; fd++) {
1207 if (fdp->fd_ofiles[fd] != NULL) {
1208 FILEDESC_SUNLOCK(fdp);
1209 (void)kern_close(td, fd);
1210 FILEDESC_SLOCK(fdp);
1213 FILEDESC_SUNLOCK(fdp);
1217 #if defined(COMPAT_43)
1219 * Return status information about a file descriptor.
1221 #ifndef _SYS_SYSPROTO_H_
1222 struct ofstat_args {
1229 ofstat(struct thread *td, struct ofstat_args *uap)
1235 error = kern_fstat(td, uap->fd, &ub);
1238 error = copyout(&oub, uap->sb, sizeof(oub));
1242 #endif /* COMPAT_43 */
1245 * Return status information about a file descriptor.
1247 #ifndef _SYS_SYSPROTO_H_
1255 fstat(struct thread *td, struct fstat_args *uap)
1260 error = kern_fstat(td, uap->fd, &ub);
1262 error = copyout(&ub, uap->sb, sizeof(ub));
1267 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1274 if ((error = fget(td, fd, &fp)) != 0)
1277 AUDIT_ARG_FILE(td->td_proc, fp);
1279 error = fo_stat(fp, sbp, td->td_ucred, td);
1282 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1289 * Return status information about a file descriptor.
1291 #ifndef _SYS_SYSPROTO_H_
1292 struct nfstat_args {
1299 nfstat(struct thread *td, struct nfstat_args *uap)
1305 error = kern_fstat(td, uap->fd, &ub);
1307 cvtnstat(&ub, &nub);
1308 error = copyout(&nub, uap->sb, sizeof(nub));
1314 * Return pathconf information about a file descriptor.
1316 #ifndef _SYS_SYSPROTO_H_
1317 struct fpathconf_args {
1324 fpathconf(struct thread *td, struct fpathconf_args *uap)
1330 if ((error = fget(td, uap->fd, &fp)) != 0)
1333 /* If asynchronous I/O is available, it works for all descriptors. */
1334 if (uap->name == _PC_ASYNC_IO) {
1335 td->td_retval[0] = async_io_version;
1341 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1342 vn_lock(vp, LK_SHARED | LK_RETRY);
1343 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1345 VFS_UNLOCK_GIANT(vfslocked);
1346 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1347 if (uap->name != _PC_PIPE_BUF) {
1350 td->td_retval[0] = PIPE_BUF;
1362 * Grow the file table to accomodate (at least) nfd descriptors. This may
1363 * block and drop the filedesc lock, but it will reacquire it before
1367 fdgrowtable(struct filedesc *fdp, int nfd)
1369 struct filedesc0 *fdp0;
1370 struct freetable *fo;
1371 struct file **ntable;
1372 struct file **otable;
1374 int nnfiles, onfiles;
1377 FILEDESC_XLOCK_ASSERT(fdp);
1379 KASSERT(fdp->fd_nfiles > 0,
1380 ("zero-length file table"));
1382 /* compute the size of the new table */
1383 onfiles = fdp->fd_nfiles;
1384 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1385 if (nnfiles <= onfiles)
1386 /* the table is already large enough */
1389 /* allocate a new table and (if required) new bitmaps */
1390 FILEDESC_XUNLOCK(fdp);
1391 ntable = malloc((nnfiles * OFILESIZE) + sizeof(struct freetable),
1392 M_FILEDESC, M_ZERO | M_WAITOK);
1393 nfileflags = (char *)&ntable[nnfiles];
1394 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1395 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE,
1396 M_FILEDESC, M_ZERO | M_WAITOK);
1399 FILEDESC_XLOCK(fdp);
1402 * We now have new tables ready to go. Since we dropped the
1403 * filedesc lock to call malloc(), watch out for a race.
1405 onfiles = fdp->fd_nfiles;
1406 if (onfiles >= nnfiles) {
1407 /* we lost the race, but that's OK */
1408 free(ntable, M_FILEDESC);
1410 free(nmap, M_FILEDESC);
1413 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1414 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1415 otable = fdp->fd_ofiles;
1416 fdp->fd_ofileflags = nfileflags;
1417 fdp->fd_ofiles = ntable;
1419 * We must preserve ofiles until the process exits because we can't
1420 * be certain that no threads have references to the old table via
1423 if (onfiles > NDFILE) {
1424 fo = (struct freetable *)&otable[onfiles];
1425 fdp0 = (struct filedesc0 *)fdp;
1426 fo->ft_table = otable;
1427 SLIST_INSERT_HEAD(&fdp0->fd_free, fo, ft_next);
1429 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1430 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1431 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1432 free(fdp->fd_map, M_FILEDESC);
1435 fdp->fd_nfiles = nnfiles;
1439 * Allocate a file descriptor for the process.
1442 fdalloc(struct thread *td, int minfd, int *result)
1444 struct proc *p = td->td_proc;
1445 struct filedesc *fdp = p->p_fd;
1448 FILEDESC_XLOCK_ASSERT(fdp);
1450 if (fdp->fd_freefile > minfd)
1451 minfd = fdp->fd_freefile;
1454 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1458 * Search the bitmap for a free descriptor. If none is found, try
1459 * to grow the file table. Keep at it until we either get a file
1460 * descriptor or run into process or system limits; fdgrowtable()
1461 * may drop the filedesc lock, so we're in a race.
1464 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1467 if (fd < fdp->fd_nfiles)
1469 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1473 * Perform some sanity checks, then mark the file descriptor as
1474 * used and return it to the caller.
1476 KASSERT(!fdisused(fdp, fd),
1477 ("fd_first_free() returned non-free descriptor"));
1478 KASSERT(fdp->fd_ofiles[fd] == NULL,
1479 ("free descriptor isn't"));
1480 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1487 * Check to see whether n user file descriptors are available to the process
1491 fdavail(struct thread *td, int n)
1493 struct proc *p = td->td_proc;
1494 struct filedesc *fdp = td->td_proc->p_fd;
1498 FILEDESC_LOCK_ASSERT(fdp);
1501 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1503 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1505 last = min(fdp->fd_nfiles, lim);
1506 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1507 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1508 if (*fpp == NULL && --n <= 0)
1515 * Create a new open file structure and allocate a file decriptor for the
1516 * process that refers to it. We add one reference to the file for the
1517 * descriptor table and one reference for resultfp. This is to prevent us
1518 * being preempted and the entry in the descriptor table closed after we
1519 * release the FILEDESC lock.
1522 fallocf(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1524 struct proc *p = td->td_proc;
1527 int maxuserfiles = maxfiles - (maxfiles / 20);
1528 static struct timeval lastfail;
1531 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1532 if ((openfiles >= maxuserfiles &&
1533 priv_check(td, PRIV_MAXFILES) != 0) ||
1534 openfiles >= maxfiles) {
1535 if (ppsratecheck(&lastfail, &curfail, 1)) {
1536 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1537 td->td_ucred->cr_ruid);
1539 uma_zfree(file_zone, fp);
1542 atomic_add_int(&openfiles, 1);
1545 * If the process has file descriptor zero open, add the new file
1546 * descriptor to the list of open files at that point, otherwise
1547 * put it at the front of the list of open files.
1549 refcount_init(&fp->f_count, 1);
1552 fp->f_cred = crhold(td->td_ucred);
1553 fp->f_ops = &badfileops;
1556 FILEDESC_XLOCK(p->p_fd);
1557 if ((error = fdalloc(td, 0, &i))) {
1558 FILEDESC_XUNLOCK(p->p_fd);
1564 p->p_fd->fd_ofiles[i] = fp;
1565 if ((flags & O_CLOEXEC) != 0)
1566 p->p_fd->fd_ofileflags[i] |= UF_EXCLOSE;
1567 FILEDESC_XUNLOCK(p->p_fd);
1576 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1579 return (fallocf(td, resultfp, resultfd, 0));
1583 * Build a new filedesc structure from another.
1584 * Copy the current, root, and jail root vnode references.
1587 fdinit(struct filedesc *fdp)
1589 struct filedesc0 *newfdp;
1591 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1592 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1594 FILEDESC_XLOCK(fdp);
1595 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1596 if (newfdp->fd_fd.fd_cdir)
1597 VREF(newfdp->fd_fd.fd_cdir);
1598 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1599 if (newfdp->fd_fd.fd_rdir)
1600 VREF(newfdp->fd_fd.fd_rdir);
1601 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1602 if (newfdp->fd_fd.fd_jdir)
1603 VREF(newfdp->fd_fd.fd_jdir);
1604 FILEDESC_XUNLOCK(fdp);
1607 /* Create the file descriptor table. */
1608 newfdp->fd_fd.fd_refcnt = 1;
1609 newfdp->fd_fd.fd_holdcnt = 1;
1610 newfdp->fd_fd.fd_cmask = CMASK;
1611 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1612 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1613 newfdp->fd_fd.fd_nfiles = NDFILE;
1614 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1615 newfdp->fd_fd.fd_lastfile = -1;
1616 return (&newfdp->fd_fd);
1619 static struct filedesc *
1620 fdhold(struct proc *p)
1622 struct filedesc *fdp;
1624 mtx_lock(&fdesc_mtx);
1628 mtx_unlock(&fdesc_mtx);
1633 fddrop(struct filedesc *fdp)
1635 struct filedesc0 *fdp0;
1636 struct freetable *ft;
1639 mtx_lock(&fdesc_mtx);
1640 i = --fdp->fd_holdcnt;
1641 mtx_unlock(&fdesc_mtx);
1645 FILEDESC_LOCK_DESTROY(fdp);
1646 fdp0 = (struct filedesc0 *)fdp;
1647 while ((ft = SLIST_FIRST(&fdp0->fd_free)) != NULL) {
1648 SLIST_REMOVE_HEAD(&fdp0->fd_free, ft_next);
1649 free(ft->ft_table, M_FILEDESC);
1651 free(fdp, M_FILEDESC);
1655 * Share a filedesc structure.
1658 fdshare(struct filedesc *fdp)
1661 FILEDESC_XLOCK(fdp);
1663 FILEDESC_XUNLOCK(fdp);
1668 * Unshare a filedesc structure, if necessary by making a copy
1671 fdunshare(struct proc *p, struct thread *td)
1674 FILEDESC_XLOCK(p->p_fd);
1675 if (p->p_fd->fd_refcnt > 1) {
1676 struct filedesc *tmp;
1678 FILEDESC_XUNLOCK(p->p_fd);
1679 tmp = fdcopy(p->p_fd);
1683 FILEDESC_XUNLOCK(p->p_fd);
1687 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1688 * this is to ease callers, not catch errors.
1691 fdcopy(struct filedesc *fdp)
1693 struct filedesc *newfdp;
1696 /* Certain daemons might not have file descriptors. */
1700 newfdp = fdinit(fdp);
1701 FILEDESC_SLOCK(fdp);
1702 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1703 FILEDESC_SUNLOCK(fdp);
1704 FILEDESC_XLOCK(newfdp);
1705 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1706 FILEDESC_XUNLOCK(newfdp);
1707 FILEDESC_SLOCK(fdp);
1709 /* copy everything except kqueue descriptors */
1710 newfdp->fd_freefile = -1;
1711 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1712 if (fdisused(fdp, i) &&
1713 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1714 fdp->fd_ofiles[i]->f_ops != &badfileops) {
1715 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1716 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1717 fhold(newfdp->fd_ofiles[i]);
1718 newfdp->fd_lastfile = i;
1720 if (newfdp->fd_freefile == -1)
1721 newfdp->fd_freefile = i;
1724 newfdp->fd_cmask = fdp->fd_cmask;
1725 FILEDESC_SUNLOCK(fdp);
1726 FILEDESC_XLOCK(newfdp);
1727 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1728 if (newfdp->fd_ofiles[i] != NULL)
1730 if (newfdp->fd_freefile == -1)
1731 newfdp->fd_freefile = i;
1732 FILEDESC_XUNLOCK(newfdp);
1737 * Release a filedesc structure.
1740 fdfree(struct thread *td)
1742 struct filedesc *fdp;
1745 struct filedesc_to_leader *fdtol;
1747 struct vnode *cdir, *jdir, *rdir, *vp;
1750 /* Certain daemons might not have file descriptors. */
1751 fdp = td->td_proc->p_fd;
1755 /* Check for special need to clear POSIX style locks */
1756 fdtol = td->td_proc->p_fdtol;
1757 if (fdtol != NULL) {
1758 FILEDESC_XLOCK(fdp);
1759 KASSERT(fdtol->fdl_refcount > 0,
1760 ("filedesc_to_refcount botch: fdl_refcount=%d",
1761 fdtol->fdl_refcount));
1762 if (fdtol->fdl_refcount == 1 &&
1763 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1764 for (i = 0, fpp = fdp->fd_ofiles;
1765 i <= fdp->fd_lastfile;
1768 (*fpp)->f_type != DTYPE_VNODE)
1772 FILEDESC_XUNLOCK(fdp);
1773 lf.l_whence = SEEK_SET;
1776 lf.l_type = F_UNLCK;
1778 locked = VFS_LOCK_GIANT(vp->v_mount);
1779 (void) VOP_ADVLOCK(vp,
1780 (caddr_t)td->td_proc->
1785 VFS_UNLOCK_GIANT(locked);
1786 FILEDESC_XLOCK(fdp);
1788 fpp = fdp->fd_ofiles + i;
1792 if (fdtol->fdl_refcount == 1) {
1793 if (fdp->fd_holdleaderscount > 0 &&
1794 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1796 * close() or do_dup() has cleared a reference
1797 * in a shared file descriptor table.
1799 fdp->fd_holdleaderswakeup = 1;
1800 sx_sleep(&fdp->fd_holdleaderscount,
1801 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1804 if (fdtol->fdl_holdcount > 0) {
1806 * Ensure that fdtol->fdl_leader remains
1807 * valid in closef().
1809 fdtol->fdl_wakeup = 1;
1810 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1815 fdtol->fdl_refcount--;
1816 if (fdtol->fdl_refcount == 0 &&
1817 fdtol->fdl_holdcount == 0) {
1818 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1819 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1822 td->td_proc->p_fdtol = NULL;
1823 FILEDESC_XUNLOCK(fdp);
1825 free(fdtol, M_FILEDESC_TO_LEADER);
1827 FILEDESC_XLOCK(fdp);
1828 i = --fdp->fd_refcnt;
1829 FILEDESC_XUNLOCK(fdp);
1833 fpp = fdp->fd_ofiles;
1834 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1836 FILEDESC_XLOCK(fdp);
1839 FILEDESC_XUNLOCK(fdp);
1840 (void) closef(fp, td);
1843 FILEDESC_XLOCK(fdp);
1845 /* XXX This should happen earlier. */
1846 mtx_lock(&fdesc_mtx);
1847 td->td_proc->p_fd = NULL;
1848 mtx_unlock(&fdesc_mtx);
1850 if (fdp->fd_nfiles > NDFILE)
1851 free(fdp->fd_ofiles, M_FILEDESC);
1852 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1853 free(fdp->fd_map, M_FILEDESC);
1857 cdir = fdp->fd_cdir;
1858 fdp->fd_cdir = NULL;
1859 rdir = fdp->fd_rdir;
1860 fdp->fd_rdir = NULL;
1861 jdir = fdp->fd_jdir;
1862 fdp->fd_jdir = NULL;
1863 FILEDESC_XUNLOCK(fdp);
1866 locked = VFS_LOCK_GIANT(cdir->v_mount);
1868 VFS_UNLOCK_GIANT(locked);
1871 locked = VFS_LOCK_GIANT(rdir->v_mount);
1873 VFS_UNLOCK_GIANT(locked);
1876 locked = VFS_LOCK_GIANT(jdir->v_mount);
1878 VFS_UNLOCK_GIANT(locked);
1885 * For setugid programs, we don't want to people to use that setugidness
1886 * to generate error messages which write to a file which otherwise would
1887 * otherwise be off-limits to the process. We check for filesystems where
1888 * the vnode can change out from under us after execve (like [lin]procfs).
1890 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1891 * sufficient. We also don't check for setugidness since we know we are.
1894 is_unsafe(struct file *fp)
1896 if (fp->f_type == DTYPE_VNODE) {
1897 struct vnode *vp = fp->f_vnode;
1899 if ((vp->v_vflag & VV_PROCDEP) != 0)
1906 * Make this setguid thing safe, if at all possible.
1909 setugidsafety(struct thread *td)
1911 struct filedesc *fdp;
1914 /* Certain daemons might not have file descriptors. */
1915 fdp = td->td_proc->p_fd;
1920 * Note: fdp->fd_ofiles may be reallocated out from under us while
1921 * we are blocked in a close. Be careful!
1923 FILEDESC_XLOCK(fdp);
1924 for (i = 0; i <= fdp->fd_lastfile; i++) {
1927 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1930 knote_fdclose(td, i);
1932 * NULL-out descriptor prior to close to avoid
1933 * a race while close blocks.
1935 fp = fdp->fd_ofiles[i];
1936 fdp->fd_ofiles[i] = NULL;
1937 fdp->fd_ofileflags[i] = 0;
1939 FILEDESC_XUNLOCK(fdp);
1940 (void) closef(fp, td);
1941 FILEDESC_XLOCK(fdp);
1944 FILEDESC_XUNLOCK(fdp);
1948 * If a specific file object occupies a specific file descriptor, close the
1949 * file descriptor entry and drop a reference on the file object. This is a
1950 * convenience function to handle a subsequent error in a function that calls
1951 * falloc() that handles the race that another thread might have closed the
1952 * file descriptor out from under the thread creating the file object.
1955 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1958 FILEDESC_XLOCK(fdp);
1959 if (fdp->fd_ofiles[idx] == fp) {
1960 fdp->fd_ofiles[idx] = NULL;
1962 FILEDESC_XUNLOCK(fdp);
1965 FILEDESC_XUNLOCK(fdp);
1969 * Close any files on exec?
1972 fdcloseexec(struct thread *td)
1974 struct filedesc *fdp;
1977 /* Certain daemons might not have file descriptors. */
1978 fdp = td->td_proc->p_fd;
1982 FILEDESC_XLOCK(fdp);
1985 * We cannot cache fd_ofiles or fd_ofileflags since operations
1986 * may block and rip them out from under us.
1988 for (i = 0; i <= fdp->fd_lastfile; i++) {
1989 if (fdp->fd_ofiles[i] != NULL &&
1990 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1991 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1994 knote_fdclose(td, i);
1996 * NULL-out descriptor prior to close to avoid
1997 * a race while close blocks.
1999 fp = fdp->fd_ofiles[i];
2000 fdp->fd_ofiles[i] = NULL;
2001 fdp->fd_ofileflags[i] = 0;
2003 if (fp->f_type == DTYPE_MQUEUE)
2004 mq_fdclose(td, i, fp);
2005 FILEDESC_XUNLOCK(fdp);
2006 (void) closef(fp, td);
2007 FILEDESC_XLOCK(fdp);
2010 FILEDESC_XUNLOCK(fdp);
2014 * It is unsafe for set[ug]id processes to be started with file
2015 * descriptors 0..2 closed, as these descriptors are given implicit
2016 * significance in the Standard C library. fdcheckstd() will create a
2017 * descriptor referencing /dev/null for each of stdin, stdout, and
2018 * stderr that is not already open.
2021 fdcheckstd(struct thread *td)
2023 struct filedesc *fdp;
2024 register_t retval, save;
2025 int i, error, devnull;
2027 fdp = td->td_proc->p_fd;
2030 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2033 for (i = 0; i < 3; i++) {
2034 if (fdp->fd_ofiles[i] != NULL)
2037 save = td->td_retval[0];
2038 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
2040 devnull = td->td_retval[0];
2041 td->td_retval[0] = save;
2044 KASSERT(devnull == i, ("oof, we didn't get our fd"));
2046 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
2055 * Internal form of close. Decrement reference count on file structure.
2056 * Note: td may be NULL when closing a file that was being passed in a
2059 * XXXRW: Giant is not required for the caller, but often will be held; this
2060 * makes it moderately likely the Giant will be recursed in the VFS case.
2063 closef(struct file *fp, struct thread *td)
2067 struct filedesc_to_leader *fdtol;
2068 struct filedesc *fdp;
2071 * POSIX record locking dictates that any close releases ALL
2072 * locks owned by this process. This is handled by setting
2073 * a flag in the unlock to free ONLY locks obeying POSIX
2074 * semantics, and not to free BSD-style file locks.
2075 * If the descriptor was in a message, POSIX-style locks
2076 * aren't passed with the descriptor, and the thread pointer
2077 * will be NULL. Callers should be careful only to pass a
2078 * NULL thread pointer when there really is no owning
2079 * context that might have locks, or the locks will be
2082 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2086 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2087 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2088 lf.l_whence = SEEK_SET;
2091 lf.l_type = F_UNLCK;
2092 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2093 F_UNLCK, &lf, F_POSIX);
2095 fdtol = td->td_proc->p_fdtol;
2096 if (fdtol != NULL) {
2098 * Handle special case where file descriptor table is
2099 * shared between multiple process leaders.
2101 fdp = td->td_proc->p_fd;
2102 FILEDESC_XLOCK(fdp);
2103 for (fdtol = fdtol->fdl_next;
2104 fdtol != td->td_proc->p_fdtol;
2105 fdtol = fdtol->fdl_next) {
2106 if ((fdtol->fdl_leader->p_flag &
2109 fdtol->fdl_holdcount++;
2110 FILEDESC_XUNLOCK(fdp);
2111 lf.l_whence = SEEK_SET;
2114 lf.l_type = F_UNLCK;
2116 (void) VOP_ADVLOCK(vp,
2117 (caddr_t)fdtol->fdl_leader,
2118 F_UNLCK, &lf, F_POSIX);
2119 FILEDESC_XLOCK(fdp);
2120 fdtol->fdl_holdcount--;
2121 if (fdtol->fdl_holdcount == 0 &&
2122 fdtol->fdl_wakeup != 0) {
2123 fdtol->fdl_wakeup = 0;
2127 FILEDESC_XUNLOCK(fdp);
2129 VFS_UNLOCK_GIANT(vfslocked);
2131 return (fdrop(fp, td));
2135 * Initialize the file pointer with the specified properties.
2137 * The ops are set with release semantics to be certain that the flags, type,
2138 * and data are visible when ops is. This is to prevent ops methods from being
2139 * called with bad data.
2142 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2147 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2151 fget_unlocked(struct filedesc *fdp, int fd)
2156 if (fd < 0 || fd >= fdp->fd_nfiles)
2159 * Fetch the descriptor locklessly. We avoid fdrop() races by
2160 * never raising a refcount above 0. To accomplish this we have
2161 * to use a cmpset loop rather than an atomic_add. The descriptor
2162 * must be re-verified once we acquire a reference to be certain
2163 * that the identity is still correct and we did not lose a race
2164 * due to preemption.
2167 fp = fdp->fd_ofiles[fd];
2170 count = fp->f_count;
2174 * Use an acquire barrier to prevent caching of fd_ofiles
2175 * so it is refreshed for verification.
2177 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) != 1)
2179 if (fp == fdp->fd_ofiles[fd])
2181 fdrop(fp, curthread);
2188 * Extract the file pointer associated with the specified descriptor for the
2189 * current user process.
2191 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2194 * If an error occured the non-zero error is returned and *fpp is set to
2195 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2196 * responsible for fdrop().
2199 _fget(struct thread *td, int fd, struct file **fpp, int flags)
2201 struct filedesc *fdp;
2205 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2207 if ((fp = fget_unlocked(fdp, fd)) == NULL)
2209 if (fp->f_ops == &badfileops) {
2214 * FREAD and FWRITE failure return EBADF as per POSIX.
2216 * Only one flag, or 0, may be specified.
2218 if ((flags == FREAD && (fp->f_flag & FREAD) == 0) ||
2219 (flags == FWRITE && (fp->f_flag & FWRITE) == 0)) {
2228 fget(struct thread *td, int fd, struct file **fpp)
2231 return(_fget(td, fd, fpp, 0));
2235 fget_read(struct thread *td, int fd, struct file **fpp)
2238 return(_fget(td, fd, fpp, FREAD));
2242 fget_write(struct thread *td, int fd, struct file **fpp)
2245 return(_fget(td, fd, fpp, FWRITE));
2249 * Like fget() but loads the underlying vnode, or returns an error if the
2250 * descriptor does not represent a vnode. Note that pipes use vnodes but
2251 * never have VM objects. The returned vnode will be vref()'d.
2253 * XXX: what about the unused flags ?
2256 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2262 if ((error = _fget(td, fd, &fp, flags)) != 0)
2264 if (fp->f_vnode == NULL) {
2276 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2279 return (_fgetvp(td, fd, vpp, 0));
2283 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2286 return (_fgetvp(td, fd, vpp, FREAD));
2291 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2294 return (_fgetvp(td, fd, vpp, FWRITE));
2299 * Like fget() but loads the underlying socket, or returns an error if the
2300 * descriptor does not represent a socket.
2302 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2305 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2306 * on their file descriptor reference to prevent the socket from being free'd
2310 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2318 if ((error = _fget(td, fd, &fp, 0)) != 0)
2320 if (fp->f_type != DTYPE_SOCKET) {
2325 *fflagp = fp->f_flag;
2336 * Drop the reference count on the socket and XXX release the SX lock in the
2337 * future. The last reference closes the socket.
2339 * Note: fputsock() is deprecated, see comment for fgetsock().
2342 fputsock(struct socket *so)
2347 CURVNET_SET(so->so_vnet);
2353 * Handle the last reference to a file being closed.
2356 _fdrop(struct file *fp, struct thread *td)
2361 if (fp->f_count != 0)
2362 panic("fdrop: count %d", fp->f_count);
2363 if (fp->f_ops != &badfileops)
2364 error = fo_close(fp, td);
2365 atomic_subtract_int(&openfiles, 1);
2367 free(fp->f_advice, M_FADVISE);
2368 uma_zfree(file_zone, fp);
2374 * Apply an advisory lock on a file descriptor.
2376 * Just attempt to get a record lock of the requested type on the entire file
2377 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2379 #ifndef _SYS_SYSPROTO_H_
2387 flock(struct thread *td, struct flock_args *uap)
2395 if ((error = fget(td, uap->fd, &fp)) != 0)
2397 if (fp->f_type != DTYPE_VNODE) {
2399 return (EOPNOTSUPP);
2403 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2404 lf.l_whence = SEEK_SET;
2407 if (uap->how & LOCK_UN) {
2408 lf.l_type = F_UNLCK;
2409 atomic_clear_int(&fp->f_flag, FHASLOCK);
2410 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2413 if (uap->how & LOCK_EX)
2414 lf.l_type = F_WRLCK;
2415 else if (uap->how & LOCK_SH)
2416 lf.l_type = F_RDLCK;
2421 atomic_set_int(&fp->f_flag, FHASLOCK);
2422 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2423 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2426 VFS_UNLOCK_GIANT(vfslocked);
2430 * Duplicate the specified descriptor to a free descriptor.
2433 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2439 * If the to-be-dup'd fd number is greater than the allowed number
2440 * of file descriptors, or the fd to be dup'd has already been
2441 * closed, then reject.
2443 FILEDESC_XLOCK(fdp);
2444 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2445 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2446 FILEDESC_XUNLOCK(fdp);
2451 * There are two cases of interest here.
2453 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2455 * For ENXIO steal away the file structure from (dfd) and store it in
2456 * (indx). (dfd) is effectively closed by this operation.
2458 * Any other error code is just returned.
2463 * Check that the mode the file is being opened for is a
2464 * subset of the mode of the existing descriptor.
2466 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2467 FILEDESC_XUNLOCK(fdp);
2470 fp = fdp->fd_ofiles[indx];
2471 fdp->fd_ofiles[indx] = wfp;
2472 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2476 FILEDESC_XUNLOCK(fdp);
2479 * We now own the reference to fp that the ofiles[]
2480 * array used to own. Release it.
2487 * Steal away the file pointer from dfd and stuff it into indx.
2489 fp = fdp->fd_ofiles[indx];
2490 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2491 fdp->fd_ofiles[dfd] = NULL;
2492 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2493 fdp->fd_ofileflags[dfd] = 0;
2497 FILEDESC_XUNLOCK(fdp);
2500 * We now own the reference to fp that the ofiles[] array
2501 * used to own. Release it.
2508 FILEDESC_XUNLOCK(fdp);
2515 * Scan all active processes and prisons to see if any of them have a current
2516 * or root directory of `olddp'. If so, replace them with the new mount point.
2519 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2521 struct filedesc *fdp;
2526 if (vrefcnt(olddp) == 1)
2529 sx_slock(&allproc_lock);
2530 FOREACH_PROC_IN_SYSTEM(p) {
2534 FILEDESC_XLOCK(fdp);
2535 if (fdp->fd_cdir == olddp) {
2537 fdp->fd_cdir = newdp;
2540 if (fdp->fd_rdir == olddp) {
2542 fdp->fd_rdir = newdp;
2545 if (fdp->fd_jdir == olddp) {
2547 fdp->fd_jdir = newdp;
2550 FILEDESC_XUNLOCK(fdp);
2553 sx_sunlock(&allproc_lock);
2554 if (rootvnode == olddp) {
2559 mtx_lock(&prison0.pr_mtx);
2560 if (prison0.pr_root == olddp) {
2562 prison0.pr_root = newdp;
2565 mtx_unlock(&prison0.pr_mtx);
2566 sx_slock(&allprison_lock);
2567 TAILQ_FOREACH(pr, &allprison, pr_list) {
2568 mtx_lock(&pr->pr_mtx);
2569 if (pr->pr_root == olddp) {
2571 pr->pr_root = newdp;
2574 mtx_unlock(&pr->pr_mtx);
2576 sx_sunlock(&allprison_lock);
2581 struct filedesc_to_leader *
2582 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2584 struct filedesc_to_leader *fdtol;
2586 fdtol = malloc(sizeof(struct filedesc_to_leader),
2587 M_FILEDESC_TO_LEADER,
2589 fdtol->fdl_refcount = 1;
2590 fdtol->fdl_holdcount = 0;
2591 fdtol->fdl_wakeup = 0;
2592 fdtol->fdl_leader = leader;
2594 FILEDESC_XLOCK(fdp);
2595 fdtol->fdl_next = old->fdl_next;
2596 fdtol->fdl_prev = old;
2597 old->fdl_next = fdtol;
2598 fdtol->fdl_next->fdl_prev = fdtol;
2599 FILEDESC_XUNLOCK(fdp);
2601 fdtol->fdl_next = fdtol;
2602 fdtol->fdl_prev = fdtol;
2608 * Get file structures globally.
2611 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2614 struct filedesc *fdp;
2619 error = sysctl_wire_old_buffer(req, 0);
2622 if (req->oldptr == NULL) {
2624 sx_slock(&allproc_lock);
2625 FOREACH_PROC_IN_SYSTEM(p) {
2626 if (p->p_state == PRS_NEW)
2631 /* overestimates sparse tables. */
2632 if (fdp->fd_lastfile > 0)
2633 n += fdp->fd_lastfile;
2636 sx_sunlock(&allproc_lock);
2637 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2640 bzero(&xf, sizeof(xf));
2641 xf.xf_size = sizeof(xf);
2642 sx_slock(&allproc_lock);
2643 FOREACH_PROC_IN_SYSTEM(p) {
2645 if (p->p_state == PRS_NEW) {
2649 if (p_cansee(req->td, p) != 0) {
2653 xf.xf_pid = p->p_pid;
2654 xf.xf_uid = p->p_ucred->cr_uid;
2659 FILEDESC_SLOCK(fdp);
2660 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2661 if ((fp = fdp->fd_ofiles[n]) == NULL)
2665 xf.xf_data = fp->f_data;
2666 xf.xf_vnode = fp->f_vnode;
2667 xf.xf_type = fp->f_type;
2668 xf.xf_count = fp->f_count;
2670 xf.xf_offset = fp->f_offset;
2671 xf.xf_flag = fp->f_flag;
2672 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2676 FILEDESC_SUNLOCK(fdp);
2681 sx_sunlock(&allproc_lock);
2685 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2686 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2688 #ifdef KINFO_OFILE_SIZE
2689 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
2692 #ifdef COMPAT_FREEBSD7
2694 export_vnode_for_osysctl(struct vnode *vp, int type,
2695 struct kinfo_ofile *kif, struct filedesc *fdp, struct sysctl_req *req)
2698 char *fullpath, *freepath;
2701 bzero(kif, sizeof(*kif));
2702 kif->kf_structsize = sizeof(*kif);
2706 kif->kf_type = KF_TYPE_VNODE;
2707 /* This function only handles directories. */
2708 if (vp->v_type != VDIR) {
2712 kif->kf_vnode_type = KF_VTYPE_VDIR;
2715 * This is not a true file descriptor, so we set a bogus refcount
2716 * and offset to indicate these fields should be ignored.
2718 kif->kf_ref_count = -1;
2719 kif->kf_offset = -1;
2723 FILEDESC_SUNLOCK(fdp);
2724 vn_fullpath(curthread, vp, &fullpath, &freepath);
2725 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2727 VFS_UNLOCK_GIANT(vfslocked);
2728 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2729 if (freepath != NULL)
2730 free(freepath, M_TEMP);
2731 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2732 FILEDESC_SLOCK(fdp);
2737 * Get per-process file descriptors for use by procstat(1), et al.
2740 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
2742 char *fullpath, *freepath;
2743 struct kinfo_ofile *kif;
2744 struct filedesc *fdp;
2745 int error, i, *name;
2746 struct shmfd *shmfd;
2755 if ((p = pfind((pid_t)name[0])) == NULL)
2757 if ((error = p_candebug(curthread, p))) {
2765 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
2766 FILEDESC_SLOCK(fdp);
2767 if (fdp->fd_cdir != NULL)
2768 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
2770 if (fdp->fd_rdir != NULL)
2771 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
2773 if (fdp->fd_jdir != NULL)
2774 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
2776 for (i = 0; i < fdp->fd_nfiles; i++) {
2777 if ((fp = fdp->fd_ofiles[i]) == NULL)
2779 bzero(kif, sizeof(*kif));
2780 kif->kf_structsize = sizeof(*kif);
2786 switch (fp->f_type) {
2788 kif->kf_type = KF_TYPE_VNODE;
2793 kif->kf_type = KF_TYPE_SOCKET;
2798 kif->kf_type = KF_TYPE_PIPE;
2802 kif->kf_type = KF_TYPE_FIFO;
2807 kif->kf_type = KF_TYPE_KQUEUE;
2811 kif->kf_type = KF_TYPE_CRYPTO;
2815 kif->kf_type = KF_TYPE_MQUEUE;
2819 kif->kf_type = KF_TYPE_SHM;
2824 kif->kf_type = KF_TYPE_SEM;
2828 kif->kf_type = KF_TYPE_PTS;
2833 kif->kf_type = KF_TYPE_UNKNOWN;
2836 kif->kf_ref_count = fp->f_count;
2837 if (fp->f_flag & FREAD)
2838 kif->kf_flags |= KF_FLAG_READ;
2839 if (fp->f_flag & FWRITE)
2840 kif->kf_flags |= KF_FLAG_WRITE;
2841 if (fp->f_flag & FAPPEND)
2842 kif->kf_flags |= KF_FLAG_APPEND;
2843 if (fp->f_flag & FASYNC)
2844 kif->kf_flags |= KF_FLAG_ASYNC;
2845 if (fp->f_flag & FFSYNC)
2846 kif->kf_flags |= KF_FLAG_FSYNC;
2847 if (fp->f_flag & FNONBLOCK)
2848 kif->kf_flags |= KF_FLAG_NONBLOCK;
2849 if (fp->f_flag & O_DIRECT)
2850 kif->kf_flags |= KF_FLAG_DIRECT;
2851 if (fp->f_flag & FHASLOCK)
2852 kif->kf_flags |= KF_FLAG_HASLOCK;
2853 kif->kf_offset = fp->f_offset;
2856 switch (vp->v_type) {
2858 kif->kf_vnode_type = KF_VTYPE_VNON;
2861 kif->kf_vnode_type = KF_VTYPE_VREG;
2864 kif->kf_vnode_type = KF_VTYPE_VDIR;
2867 kif->kf_vnode_type = KF_VTYPE_VBLK;
2870 kif->kf_vnode_type = KF_VTYPE_VCHR;
2873 kif->kf_vnode_type = KF_VTYPE_VLNK;
2876 kif->kf_vnode_type = KF_VTYPE_VSOCK;
2879 kif->kf_vnode_type = KF_VTYPE_VFIFO;
2882 kif->kf_vnode_type = KF_VTYPE_VBAD;
2885 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
2889 * It is OK to drop the filedesc lock here as we will
2890 * re-validate and re-evaluate its properties when
2891 * the loop continues.
2895 FILEDESC_SUNLOCK(fdp);
2896 vn_fullpath(curthread, vp, &fullpath, &freepath);
2897 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2899 VFS_UNLOCK_GIANT(vfslocked);
2900 strlcpy(kif->kf_path, fullpath,
2901 sizeof(kif->kf_path));
2902 if (freepath != NULL)
2903 free(freepath, M_TEMP);
2904 FILEDESC_SLOCK(fdp);
2907 struct sockaddr *sa;
2909 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
2910 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
2911 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
2914 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
2915 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
2916 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
2919 kif->kf_sock_domain =
2920 so->so_proto->pr_domain->dom_family;
2921 kif->kf_sock_type = so->so_type;
2922 kif->kf_sock_protocol = so->so_proto->pr_protocol;
2925 strlcpy(kif->kf_path, tty_devname(tp),
2926 sizeof(kif->kf_path));
2929 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
2930 error = SYSCTL_OUT(req, kif, sizeof(*kif));
2934 FILEDESC_SUNLOCK(fdp);
2940 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, CTLFLAG_RD,
2941 sysctl_kern_proc_ofiledesc, "Process ofiledesc entries");
2942 #endif /* COMPAT_FREEBSD7 */
2944 #ifdef KINFO_FILE_SIZE
2945 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
2949 export_vnode_for_sysctl(struct vnode *vp, int type,
2950 struct kinfo_file *kif, struct filedesc *fdp, struct sysctl_req *req)
2953 char *fullpath, *freepath;
2956 bzero(kif, sizeof(*kif));
2960 kif->kf_type = KF_TYPE_VNODE;
2961 /* This function only handles directories. */
2962 if (vp->v_type != VDIR) {
2966 kif->kf_vnode_type = KF_VTYPE_VDIR;
2969 * This is not a true file descriptor, so we set a bogus refcount
2970 * and offset to indicate these fields should be ignored.
2972 kif->kf_ref_count = -1;
2973 kif->kf_offset = -1;
2977 FILEDESC_SUNLOCK(fdp);
2978 vn_fullpath(curthread, vp, &fullpath, &freepath);
2979 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2981 VFS_UNLOCK_GIANT(vfslocked);
2982 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2983 if (freepath != NULL)
2984 free(freepath, M_TEMP);
2985 /* Pack record size down */
2986 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
2987 strlen(kif->kf_path) + 1;
2988 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
2989 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
2990 FILEDESC_SLOCK(fdp);
2995 * Get per-process file descriptors for use by procstat(1), et al.
2998 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3000 char *fullpath, *freepath;
3001 struct kinfo_file *kif;
3002 struct filedesc *fdp;
3003 int error, i, *name;
3004 struct shmfd *shmfd;
3014 if ((p = pfind((pid_t)name[0])) == NULL)
3016 if ((error = p_candebug(curthread, p))) {
3024 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3025 FILEDESC_SLOCK(fdp);
3026 if (fdp->fd_cdir != NULL)
3027 export_vnode_for_sysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3029 if (fdp->fd_rdir != NULL)
3030 export_vnode_for_sysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3032 if (fdp->fd_jdir != NULL)
3033 export_vnode_for_sysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3035 for (i = 0; i < fdp->fd_nfiles; i++) {
3036 if ((fp = fdp->fd_ofiles[i]) == NULL)
3038 bzero(kif, sizeof(*kif));
3044 switch (fp->f_type) {
3046 kif->kf_type = KF_TYPE_VNODE;
3051 kif->kf_type = KF_TYPE_SOCKET;
3056 kif->kf_type = KF_TYPE_PIPE;
3060 kif->kf_type = KF_TYPE_FIFO;
3065 kif->kf_type = KF_TYPE_KQUEUE;
3069 kif->kf_type = KF_TYPE_CRYPTO;
3073 kif->kf_type = KF_TYPE_MQUEUE;
3077 kif->kf_type = KF_TYPE_SHM;
3082 kif->kf_type = KF_TYPE_SEM;
3086 kif->kf_type = KF_TYPE_PTS;
3091 kif->kf_type = KF_TYPE_UNKNOWN;
3094 kif->kf_ref_count = fp->f_count;
3095 if (fp->f_flag & FREAD)
3096 kif->kf_flags |= KF_FLAG_READ;
3097 if (fp->f_flag & FWRITE)
3098 kif->kf_flags |= KF_FLAG_WRITE;
3099 if (fp->f_flag & FAPPEND)
3100 kif->kf_flags |= KF_FLAG_APPEND;
3101 if (fp->f_flag & FASYNC)
3102 kif->kf_flags |= KF_FLAG_ASYNC;
3103 if (fp->f_flag & FFSYNC)
3104 kif->kf_flags |= KF_FLAG_FSYNC;
3105 if (fp->f_flag & FNONBLOCK)
3106 kif->kf_flags |= KF_FLAG_NONBLOCK;
3107 if (fp->f_flag & O_DIRECT)
3108 kif->kf_flags |= KF_FLAG_DIRECT;
3109 if (fp->f_flag & FHASLOCK)
3110 kif->kf_flags |= KF_FLAG_HASLOCK;
3111 kif->kf_offset = fp->f_offset;
3114 switch (vp->v_type) {
3116 kif->kf_vnode_type = KF_VTYPE_VNON;
3119 kif->kf_vnode_type = KF_VTYPE_VREG;
3122 kif->kf_vnode_type = KF_VTYPE_VDIR;
3125 kif->kf_vnode_type = KF_VTYPE_VBLK;
3128 kif->kf_vnode_type = KF_VTYPE_VCHR;
3131 kif->kf_vnode_type = KF_VTYPE_VLNK;
3134 kif->kf_vnode_type = KF_VTYPE_VSOCK;
3137 kif->kf_vnode_type = KF_VTYPE_VFIFO;
3140 kif->kf_vnode_type = KF_VTYPE_VBAD;
3143 kif->kf_vnode_type = KF_VTYPE_UNKNOWN;
3147 * It is OK to drop the filedesc lock here as we will
3148 * re-validate and re-evaluate its properties when
3149 * the loop continues.
3153 FILEDESC_SUNLOCK(fdp);
3154 vn_fullpath(curthread, vp, &fullpath, &freepath);
3155 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
3157 VFS_UNLOCK_GIANT(vfslocked);
3158 strlcpy(kif->kf_path, fullpath,
3159 sizeof(kif->kf_path));
3160 if (freepath != NULL)
3161 free(freepath, M_TEMP);
3162 FILEDESC_SLOCK(fdp);
3165 struct sockaddr *sa;
3167 if (so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa)
3168 == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
3169 bcopy(sa, &kif->kf_sa_local, sa->sa_len);
3172 if (so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa)
3173 == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
3174 bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
3177 kif->kf_sock_domain =
3178 so->so_proto->pr_domain->dom_family;
3179 kif->kf_sock_type = so->so_type;
3180 kif->kf_sock_protocol = so->so_proto->pr_protocol;
3183 strlcpy(kif->kf_path, tty_devname(tp),
3184 sizeof(kif->kf_path));
3187 shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
3188 /* Pack record size down */
3189 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3190 strlen(kif->kf_path) + 1;
3191 kif->kf_structsize = roundup(kif->kf_structsize,
3193 oldidx = req->oldidx;
3194 error = SYSCTL_OUT(req, kif, kif->kf_structsize);
3196 if (error == ENOMEM) {
3198 * The hack to keep the ABI of sysctl
3199 * kern.proc.filedesc intact, but not
3200 * to account a partially copied
3201 * kinfo_file into the oldidx.
3203 req->oldidx = oldidx;
3209 FILEDESC_SUNLOCK(fdp);
3215 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
3216 sysctl_kern_proc_filedesc, "Process filedesc entries");
3220 * For the purposes of debugging, generate a human-readable string for the
3224 file_type_to_name(short type)
3254 * For the purposes of debugging, identify a process (if any, perhaps one of
3255 * many) that references the passed file in its file descriptor array. Return
3258 static struct proc *
3259 file_to_first_proc(struct file *fp)
3261 struct filedesc *fdp;
3265 FOREACH_PROC_IN_SYSTEM(p) {
3266 if (p->p_state == PRS_NEW)
3271 for (n = 0; n < fdp->fd_nfiles; n++) {
3272 if (fp == fdp->fd_ofiles[n])
3280 db_print_file(struct file *fp, int header)
3285 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3286 "File", "Type", "Data", "Flag", "GCFl", "Count",
3287 "MCount", "Vnode", "FPID", "FCmd");
3288 p = file_to_first_proc(fp);
3289 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3290 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3291 0, fp->f_count, 0, fp->f_vnode,
3292 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3295 DB_SHOW_COMMAND(file, db_show_file)
3300 db_printf("usage: show file <addr>\n");
3303 fp = (struct file *)addr;
3304 db_print_file(fp, 1);
3307 DB_SHOW_COMMAND(files, db_show_files)
3309 struct filedesc *fdp;
3316 FOREACH_PROC_IN_SYSTEM(p) {
3317 if (p->p_state == PRS_NEW)
3319 if ((fdp = p->p_fd) == NULL)
3321 for (n = 0; n < fdp->fd_nfiles; ++n) {
3322 if ((fp = fdp->fd_ofiles[n]) == NULL)
3324 db_print_file(fp, header);
3331 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3332 &maxfilesperproc, 0, "Maximum files allowed open per process");
3334 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3335 &maxfiles, 0, "Maximum number of files");
3337 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3338 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3342 filelistinit(void *dummy)
3345 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3346 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3347 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3348 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
3350 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3352 /*-------------------------------------------------------------------*/
3355 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
3362 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, struct thread *td)
3369 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
3376 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
3383 badfo_kqfilter(struct file *fp, struct knote *kn)
3390 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
3397 badfo_close(struct file *fp, struct thread *td)
3403 struct fileops badfileops = {
3404 .fo_read = badfo_readwrite,
3405 .fo_write = badfo_readwrite,
3406 .fo_truncate = badfo_truncate,
3407 .fo_ioctl = badfo_ioctl,
3408 .fo_poll = badfo_poll,
3409 .fo_kqfilter = badfo_kqfilter,
3410 .fo_stat = badfo_stat,
3411 .fo_close = badfo_close,
3415 /*-------------------------------------------------------------------*/
3418 * File Descriptor pseudo-device driver (/dev/fd/).
3420 * Opening minor device N dup()s the file (if any) connected to file
3421 * descriptor N belonging to the calling process. Note that this driver
3422 * consists of only the ``open()'' routine, because all subsequent
3423 * references to this file will be direct to the other driver.
3425 * XXX: we could give this one a cloning event handler if necessary.
3430 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3434 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3435 * the file descriptor being sought for duplication. The error
3436 * return ensures that the vnode for this device will be released
3437 * by vn_open. Open will detect this special error and take the
3438 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3439 * will simply report the error.
3441 td->td_dupfd = dev2unit(dev);
3445 static struct cdevsw fildesc_cdevsw = {
3446 .d_version = D_VERSION,
3452 fildesc_drvinit(void *unused)
3456 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3457 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3458 make_dev_alias(dev, "stdin");
3459 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3460 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3461 make_dev_alias(dev, "stdout");
3462 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3463 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3464 make_dev_alias(dev, "stderr");
3467 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);