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"
43 #include <sys/param.h>
44 #include <sys/systm.h>
47 #include <sys/fcntl.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mqueue.h>
58 #include <sys/mutex.h>
59 #include <sys/namei.h>
61 #include <sys/resourcevar.h>
62 #include <sys/signalvar.h>
63 #include <sys/socketvar.h>
66 #include <sys/syscallsubr.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysproto.h>
69 #include <sys/unistd.h>
70 #include <sys/vnode.h>
72 #include <security/audit/audit.h>
78 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
79 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
80 "file desc to leader structures");
81 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
83 static uma_zone_t file_zone;
86 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
87 enum dup_type { DUP_VARIABLE, DUP_FIXED };
89 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
91 static int fd_first_free(struct filedesc *, int, int);
92 static int fd_last_used(struct filedesc *, int, int);
93 static void fdgrowtable(struct filedesc *, int);
94 static int fdrop_locked(struct file *fp, struct thread *td);
95 static void fdunused(struct filedesc *fdp, int fd);
96 static void fdused(struct filedesc *fdp, int fd);
99 * A process is initially started out with NDFILE descriptors stored within
100 * this structure, selected to be enough for typical applications based on
101 * the historical limit of 20 open files (and the usage of descriptors by
102 * shells). If these descriptors are exhausted, a larger descriptor table
103 * may be allocated, up to a process' resource limit; the internal arrays
107 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
108 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
109 #define NDSLOT(x) ((x) / NDENTRIES)
110 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
111 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
114 * Storage required per open file descriptor.
116 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
119 * Basic allocation of descriptors:
120 * one of the above, plus arrays for NDFILE descriptors.
123 struct filedesc fd_fd;
125 * These arrays are used when the number of open files is
126 * <= NDFILE, and are then pointed to by the pointers above.
128 struct file *fd_dfiles[NDFILE];
129 char fd_dfileflags[NDFILE];
130 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
134 * Descriptor management.
136 struct filelist filehead; /* head of list of open files */
137 int openfiles; /* actual number of open files */
138 struct sx filelist_lock; /* sx to protect filelist */
139 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
140 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
142 /* A mutex to protect the association between a proc and filedesc. */
143 static struct mtx fdesc_mtx;
146 * Find the first zero bit in the given bitmap, starting at low and not
147 * exceeding size - 1.
150 fd_first_free(struct filedesc *fdp, int low, int size)
152 NDSLOTTYPE *map = fdp->fd_map;
160 if (low % NDENTRIES) {
161 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
162 if ((mask &= ~map[off]) != 0UL)
163 return (off * NDENTRIES + ffsl(mask) - 1);
166 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
167 if (map[off] != ~0UL)
168 return (off * NDENTRIES + ffsl(~map[off]) - 1);
173 * Find the highest non-zero bit in the given bitmap, starting at low and
174 * not exceeding size - 1.
177 fd_last_used(struct filedesc *fdp, int low, int size)
179 NDSLOTTYPE *map = fdp->fd_map;
187 if (size % NDENTRIES) {
188 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
189 if ((mask &= map[off]) != 0)
190 return (off * NDENTRIES + flsl(mask) - 1);
193 for (minoff = NDSLOT(low); off >= minoff; --off)
195 return (off * NDENTRIES + flsl(map[off]) - 1);
200 fdisused(struct filedesc *fdp, int fd)
202 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
203 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
204 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
208 * Mark a file descriptor as used.
211 fdused(struct filedesc *fdp, int fd)
213 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
214 KASSERT(!fdisused(fdp, fd),
215 ("fd already used"));
216 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
217 if (fd > fdp->fd_lastfile)
218 fdp->fd_lastfile = fd;
219 if (fd == fdp->fd_freefile)
220 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
224 * Mark a file descriptor as unused.
227 fdunused(struct filedesc *fdp, int fd)
229 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
230 KASSERT(fdisused(fdp, fd),
231 ("fd is already unused"));
232 KASSERT(fdp->fd_ofiles[fd] == NULL,
233 ("fd is still in use"));
234 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
235 if (fd < fdp->fd_freefile)
236 fdp->fd_freefile = fd;
237 if (fd == fdp->fd_lastfile)
238 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
242 * System calls on descriptors.
244 #ifndef _SYS_SYSPROTO_H_
245 struct getdtablesize_args {
254 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
256 struct proc *p = td->td_proc;
260 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
266 * Duplicate a file descriptor to a particular value.
268 * note: keep in mind that a potential race condition exists when closing
269 * descriptors from a shared descriptor table (via rfork).
271 #ifndef _SYS_SYSPROTO_H_
282 dup2(struct thread *td, struct dup2_args *uap)
285 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
290 * Duplicate a file descriptor.
292 #ifndef _SYS_SYSPROTO_H_
302 dup(struct thread *td, struct dup_args *uap)
305 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
309 * The file control system call.
311 #ifndef _SYS_SYSPROTO_H_
323 fcntl(struct thread *td, struct fcntl_args *uap)
334 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
343 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
346 if (uap->cmd == F_GETLK)
347 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
352 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
354 struct filedesc *fdp;
365 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
366 * avoid grabbing Giant for calls we know don't need it.
386 if ((unsigned)fd >= fdp->fd_nfiles ||
387 (fp = fdp->fd_ofiles[fd]) == NULL) {
388 FILEDESC_UNLOCK(fdp);
392 pop = &fdp->fd_ofileflags[fd];
396 /* mtx_assert(&Giant, MA_NOTOWNED); */
397 FILEDESC_UNLOCK(fdp);
400 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
401 newmin >= maxfilesperproc) {
407 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
411 /* mtx_assert(&Giant, MA_NOTOWNED); */
412 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
413 FILEDESC_UNLOCK(fdp);
417 /* mtx_assert(&Giant, MA_NOTOWNED); */
418 *pop = (*pop &~ UF_EXCLOSE) |
419 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
420 FILEDESC_UNLOCK(fdp);
424 /* mtx_assert(&Giant, MA_NOTOWNED); */
426 td->td_retval[0] = OFLAGS(fp->f_flag);
428 FILEDESC_UNLOCK(fdp);
432 mtx_assert(&Giant, MA_OWNED);
435 fp->f_flag &= ~FCNTLFLAGS;
436 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
438 FILEDESC_UNLOCK(fdp);
439 tmp = fp->f_flag & FNONBLOCK;
440 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
445 tmp = fp->f_flag & FASYNC;
446 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
452 fp->f_flag &= ~FNONBLOCK;
455 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
460 mtx_assert(&Giant, MA_OWNED);
462 FILEDESC_UNLOCK(fdp);
463 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
465 td->td_retval[0] = tmp;
470 mtx_assert(&Giant, MA_OWNED);
472 FILEDESC_UNLOCK(fdp);
474 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
479 mtx_assert(&Giant, MA_OWNED);
481 /* FALLTHROUGH F_SETLK */
484 mtx_assert(&Giant, MA_OWNED);
485 if (fp->f_type != DTYPE_VNODE) {
486 FILEDESC_UNLOCK(fdp);
491 flp = (struct flock *)arg;
492 if (flp->l_whence == SEEK_CUR) {
493 if (fp->f_offset < 0 ||
495 fp->f_offset > OFF_MAX - flp->l_start)) {
496 FILEDESC_UNLOCK(fdp);
500 flp->l_start += fp->f_offset;
504 * VOP_ADVLOCK() may block.
507 FILEDESC_UNLOCK(fdp);
510 switch (flp->l_type) {
512 if ((fp->f_flag & FREAD) == 0) {
516 PROC_LOCK(p->p_leader);
517 p->p_leader->p_flag |= P_ADVLOCK;
518 PROC_UNLOCK(p->p_leader);
519 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
523 if ((fp->f_flag & FWRITE) == 0) {
527 PROC_LOCK(p->p_leader);
528 p->p_leader->p_flag |= P_ADVLOCK;
529 PROC_UNLOCK(p->p_leader);
530 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
534 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
541 /* Check for race with close */
542 FILEDESC_LOCK_FAST(fdp);
543 if ((unsigned) fd >= fdp->fd_nfiles ||
544 fp != fdp->fd_ofiles[fd]) {
545 FILEDESC_UNLOCK_FAST(fdp);
546 flp->l_whence = SEEK_SET;
549 flp->l_type = F_UNLCK;
550 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
551 F_UNLCK, flp, F_POSIX);
553 FILEDESC_UNLOCK_FAST(fdp);
558 mtx_assert(&Giant, MA_OWNED);
559 if (fp->f_type != DTYPE_VNODE) {
560 FILEDESC_UNLOCK(fdp);
564 flp = (struct flock *)arg;
565 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
566 flp->l_type != F_UNLCK) {
567 FILEDESC_UNLOCK(fdp);
571 if (flp->l_whence == SEEK_CUR) {
572 if ((flp->l_start > 0 &&
573 fp->f_offset > OFF_MAX - flp->l_start) ||
575 fp->f_offset < OFF_MIN - flp->l_start)) {
576 FILEDESC_UNLOCK(fdp);
580 flp->l_start += fp->f_offset;
583 * VOP_ADVLOCK() may block.
586 FILEDESC_UNLOCK(fdp);
588 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
593 FILEDESC_UNLOCK(fdp);
604 * Common code for dup, dup2, and fcntl(F_DUPFD).
607 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
609 struct filedesc *fdp;
613 int error, holdleaders, maxfd;
615 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
616 ("invalid dup type %d", type));
622 * Verify we have a valid descriptor to dup from and possibly to
625 if (old < 0 || new < 0)
628 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
634 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
635 FILEDESC_UNLOCK(fdp);
638 if (type == DUP_FIXED && old == new) {
640 FILEDESC_UNLOCK(fdp);
643 fp = fdp->fd_ofiles[old];
647 * If the caller specified a file descriptor, make sure the file
648 * table is large enough to hold it, and grab it. Otherwise, just
649 * allocate a new descriptor the usual way. Since the filedesc
650 * lock may be temporarily dropped in the process, we have to look
653 if (type == DUP_FIXED) {
654 if (new >= fdp->fd_nfiles)
655 fdgrowtable(fdp, new + 1);
656 if (fdp->fd_ofiles[new] == NULL)
659 if ((error = fdalloc(td, new, &new)) != 0) {
660 FILEDESC_UNLOCK(fdp);
667 * If the old file changed out from under us then treat it as a
668 * bad file descriptor. Userland should do its own locking to
671 if (fdp->fd_ofiles[old] != fp) {
672 /* we've allocated a descriptor which we won't use */
673 if (fdp->fd_ofiles[new] == NULL)
675 FILEDESC_UNLOCK(fdp);
680 ("new fd is same as old"));
683 * Save info on the descriptor being overwritten. We cannot close
684 * it without introducing an ownership race for the slot, since we
685 * need to drop the filedesc lock to call closef().
687 * XXX this duplicates parts of close().
689 delfp = fdp->fd_ofiles[new];
692 if (td->td_proc->p_fdtol != NULL) {
694 * Ask fdfree() to sleep to ensure that all relevant
695 * process leaders can be traversed in closef().
697 fdp->fd_holdleaderscount++;
703 * Duplicate the source descriptor
705 fdp->fd_ofiles[new] = fp;
706 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
707 if (new > fdp->fd_lastfile)
708 fdp->fd_lastfile = new;
712 * If we dup'd over a valid file, we now own the reference to it
713 * and must dispose of it using closef() semantics (as if a
714 * close() were performed on it).
716 * XXX this duplicates parts of close().
719 knote_fdclose(td, new);
720 if (delfp->f_type == DTYPE_MQUEUE)
721 mq_fdclose(td, new, delfp);
722 FILEDESC_UNLOCK(fdp);
723 (void) closef(delfp, td);
725 FILEDESC_LOCK_FAST(fdp);
726 fdp->fd_holdleaderscount--;
727 if (fdp->fd_holdleaderscount == 0 &&
728 fdp->fd_holdleaderswakeup != 0) {
729 fdp->fd_holdleaderswakeup = 0;
730 wakeup(&fdp->fd_holdleaderscount);
732 FILEDESC_UNLOCK_FAST(fdp);
735 FILEDESC_UNLOCK(fdp);
741 * If sigio is on the list associated with a process or process group,
742 * disable signalling from the device, remove sigio from the list and
746 funsetown(struct sigio **sigiop)
756 *(sigio->sio_myref) = NULL;
757 if ((sigio)->sio_pgid < 0) {
758 struct pgrp *pg = (sigio)->sio_pgrp;
760 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
764 struct proc *p = (sigio)->sio_proc;
766 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
771 crfree(sigio->sio_ucred);
772 FREE(sigio, M_SIGIO);
776 * Free a list of sigio structures.
777 * We only need to lock the SIGIO_LOCK because we have made ourselves
778 * inaccessible to callers of fsetown and therefore do not need to lock
779 * the proc or pgrp struct for the list manipulation.
782 funsetownlst(struct sigiolst *sigiolst)
788 sigio = SLIST_FIRST(sigiolst);
795 * Every entry of the list should belong
796 * to a single proc or pgrp.
798 if (sigio->sio_pgid < 0) {
799 pg = sigio->sio_pgrp;
800 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
801 } else /* if (sigio->sio_pgid > 0) */ {
803 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
807 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
808 *(sigio->sio_myref) = NULL;
810 KASSERT(sigio->sio_pgid < 0,
811 ("Proc sigio in pgrp sigio list"));
812 KASSERT(sigio->sio_pgrp == pg,
813 ("Bogus pgrp in sigio list"));
815 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
818 } else /* if (p != NULL) */ {
819 KASSERT(sigio->sio_pgid > 0,
820 ("Pgrp sigio in proc sigio list"));
821 KASSERT(sigio->sio_proc == p,
822 ("Bogus proc in sigio list"));
824 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
829 crfree(sigio->sio_ucred);
830 FREE(sigio, M_SIGIO);
837 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
839 * After permission checking, add a sigio structure to the sigio list for
840 * the process or process group.
843 fsetown(pid_t pgid, struct sigio **sigiop)
857 /* Allocate and fill in the new sigio out of locks. */
858 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
859 sigio->sio_pgid = pgid;
860 sigio->sio_ucred = crhold(curthread->td_ucred);
861 sigio->sio_myref = sigiop;
863 sx_slock(&proctree_lock);
872 * Policy - Don't allow a process to FSETOWN a process
873 * in another session.
875 * Remove this test to allow maximum flexibility or
876 * restrict FSETOWN to the current process or process
877 * group for maximum safety.
880 if (proc->p_session != curthread->td_proc->p_session) {
886 } else /* if (pgid < 0) */ {
887 pgrp = pgfind(-pgid);
895 * Policy - Don't allow a process to FSETOWN a process
896 * in another session.
898 * Remove this test to allow maximum flexibility or
899 * restrict FSETOWN to the current process or process
900 * group for maximum safety.
902 if (pgrp->pg_session != curthread->td_proc->p_session) {
913 * Since funsetownlst() is called without the proctree
914 * locked, we need to check for P_WEXIT.
915 * XXX: is ESRCH correct?
917 if ((proc->p_flag & P_WEXIT) != 0) {
922 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
923 sigio->sio_proc = proc;
927 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
928 sigio->sio_pgrp = pgrp;
931 sx_sunlock(&proctree_lock);
938 sx_sunlock(&proctree_lock);
939 crfree(sigio->sio_ucred);
940 FREE(sigio, M_SIGIO);
945 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
949 struct sigio **sigiop;
954 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
960 * Close a file descriptor.
962 #ifndef _SYS_SYSPROTO_H_
974 struct close_args *uap;
976 struct filedesc *fdp;
984 fdp = td->td_proc->p_fd;
986 AUDIT_SYSCLOSE(td, fd);
989 if ((unsigned)fd >= fdp->fd_nfiles ||
990 (fp = fdp->fd_ofiles[fd]) == NULL) {
991 FILEDESC_UNLOCK(fdp);
994 fdp->fd_ofiles[fd] = NULL;
995 fdp->fd_ofileflags[fd] = 0;
997 if (td->td_proc->p_fdtol != NULL) {
999 * Ask fdfree() to sleep to ensure that all relevant
1000 * process leaders can be traversed in closef().
1002 fdp->fd_holdleaderscount++;
1007 * We now hold the fp reference that used to be owned by the descriptor
1009 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1010 * race of the fd getting opened, a knote added, and deleteing a knote
1013 knote_fdclose(td, fd);
1014 if (fp->f_type == DTYPE_MQUEUE)
1015 mq_fdclose(td, fd, fp);
1016 FILEDESC_UNLOCK(fdp);
1018 error = closef(fp, td);
1020 FILEDESC_LOCK_FAST(fdp);
1021 fdp->fd_holdleaderscount--;
1022 if (fdp->fd_holdleaderscount == 0 &&
1023 fdp->fd_holdleaderswakeup != 0) {
1024 fdp->fd_holdleaderswakeup = 0;
1025 wakeup(&fdp->fd_holdleaderscount);
1027 FILEDESC_UNLOCK_FAST(fdp);
1032 #if defined(COMPAT_43)
1034 * Return status information about a file descriptor.
1036 #ifndef _SYS_SYSPROTO_H_
1037 struct ofstat_args {
1047 ofstat(struct thread *td, struct ofstat_args *uap)
1053 error = kern_fstat(td, uap->fd, &ub);
1056 error = copyout(&oub, uap->sb, sizeof(oub));
1060 #endif /* COMPAT_43 */
1063 * Return status information about a file descriptor.
1065 #ifndef _SYS_SYSPROTO_H_
1076 fstat(struct thread *td, struct fstat_args *uap)
1081 error = kern_fstat(td, uap->fd, &ub);
1083 error = copyout(&ub, uap->sb, sizeof(ub));
1088 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1095 if ((error = fget(td, fd, &fp)) != 0)
1098 AUDIT_ARG(file, td->td_proc, fp);
1100 error = fo_stat(fp, sbp, td->td_ucred, td);
1106 * Return status information about a file descriptor.
1108 #ifndef _SYS_SYSPROTO_H_
1109 struct nfstat_args {
1119 nfstat(struct thread *td, struct nfstat_args *uap)
1125 error = kern_fstat(td, uap->fd, &ub);
1127 cvtnstat(&ub, &nub);
1128 error = copyout(&nub, uap->sb, sizeof(nub));
1134 * Return pathconf information about a file descriptor.
1136 #ifndef _SYS_SYSPROTO_H_
1137 struct fpathconf_args {
1147 fpathconf(struct thread *td, struct fpathconf_args *uap)
1153 if ((error = fget(td, uap->fd, &fp)) != 0)
1156 /* If asynchronous I/O is available, it works for all descriptors. */
1157 if (uap->name == _PC_ASYNC_IO) {
1158 td->td_retval[0] = async_io_version;
1164 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1165 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1166 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1167 VOP_UNLOCK(vp, 0, td);
1168 VFS_UNLOCK_GIANT(vfslocked);
1169 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1170 if (uap->name != _PC_PIPE_BUF) {
1173 td->td_retval[0] = PIPE_BUF;
1185 * Grow the file table to accomodate (at least) nfd descriptors. This may
1186 * block and drop the filedesc lock, but it will reacquire it before
1190 fdgrowtable(struct filedesc *fdp, int nfd)
1192 struct file **ntable;
1194 int nnfiles, onfiles;
1197 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1199 KASSERT(fdp->fd_nfiles > 0,
1200 ("zero-length file table"));
1202 /* compute the size of the new table */
1203 onfiles = fdp->fd_nfiles;
1204 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1205 if (nnfiles <= onfiles)
1206 /* the table is already large enough */
1209 /* allocate a new table and (if required) new bitmaps */
1210 FILEDESC_UNLOCK(fdp);
1211 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1212 M_FILEDESC, M_ZERO | M_WAITOK);
1213 nfileflags = (char *)&ntable[nnfiles];
1214 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1215 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1216 M_FILEDESC, M_ZERO | M_WAITOK);
1222 * We now have new tables ready to go. Since we dropped the
1223 * filedesc lock to call malloc(), watch out for a race.
1225 onfiles = fdp->fd_nfiles;
1226 if (onfiles >= nnfiles) {
1227 /* we lost the race, but that's OK */
1228 free(ntable, M_FILEDESC);
1230 free(nmap, M_FILEDESC);
1233 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1234 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1235 if (onfiles > NDFILE)
1236 free(fdp->fd_ofiles, M_FILEDESC);
1237 fdp->fd_ofiles = ntable;
1238 fdp->fd_ofileflags = nfileflags;
1239 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1240 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1241 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1242 free(fdp->fd_map, M_FILEDESC);
1245 fdp->fd_nfiles = nnfiles;
1249 * Allocate a file descriptor for the process.
1252 fdalloc(struct thread *td, int minfd, int *result)
1254 struct proc *p = td->td_proc;
1255 struct filedesc *fdp = p->p_fd;
1258 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1260 if (fdp->fd_freefile > minfd)
1261 minfd = fdp->fd_freefile;
1264 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1268 * Search the bitmap for a free descriptor. If none is found, try
1269 * to grow the file table. Keep at it until we either get a file
1270 * descriptor or run into process or system limits; fdgrowtable()
1271 * may drop the filedesc lock, so we're in a race.
1274 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1277 if (fd < fdp->fd_nfiles)
1279 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1283 * Perform some sanity checks, then mark the file descriptor as
1284 * used and return it to the caller.
1286 KASSERT(!fdisused(fdp, fd),
1287 ("fd_first_free() returned non-free descriptor"));
1288 KASSERT(fdp->fd_ofiles[fd] == NULL,
1289 ("free descriptor isn't"));
1290 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1297 * Check to see whether n user file descriptors
1298 * are available to the process p.
1301 fdavail(struct thread *td, int n)
1303 struct proc *p = td->td_proc;
1304 struct filedesc *fdp = td->td_proc->p_fd;
1308 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1311 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1313 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1315 last = min(fdp->fd_nfiles, lim);
1316 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1317 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1318 if (*fpp == NULL && --n <= 0)
1325 * Create a new open file structure and allocate
1326 * a file decriptor for the process that refers to it.
1327 * We add one reference to the file for the descriptor table
1328 * and one reference for resultfp. This is to prevent us being
1329 * preempted and the entry in the descriptor table closed after
1330 * we release the FILEDESC lock.
1333 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1335 struct proc *p = td->td_proc;
1336 struct file *fp, *fq;
1338 int maxuserfiles = maxfiles - (maxfiles / 20);
1339 static struct timeval lastfail;
1342 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1343 sx_xlock(&filelist_lock);
1345 if ((openfiles >= maxuserfiles &&
1346 suser_cred(td->td_ucred, SUSER_RUID) != 0) ||
1347 openfiles >= maxfiles) {
1348 if (ppsratecheck(&lastfail, &curfail, 1)) {
1349 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1350 td->td_ucred->cr_ruid);
1352 sx_xunlock(&filelist_lock);
1353 uma_zfree(file_zone, fp);
1359 * If the process has file descriptor zero open, add the new file
1360 * descriptor to the list of open files at that point, otherwise
1361 * put it at the front of the list of open files.
1363 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1367 fp->f_cred = crhold(td->td_ucred);
1368 fp->f_ops = &badfileops;
1371 FILEDESC_LOCK(p->p_fd);
1372 if ((fq = p->p_fd->fd_ofiles[0])) {
1373 LIST_INSERT_AFTER(fq, fp, f_list);
1375 LIST_INSERT_HEAD(&filehead, fp, f_list);
1377 sx_xunlock(&filelist_lock);
1378 if ((error = fdalloc(td, 0, &i))) {
1379 FILEDESC_UNLOCK(p->p_fd);
1385 p->p_fd->fd_ofiles[i] = fp;
1386 FILEDESC_UNLOCK(p->p_fd);
1395 * Build a new filedesc structure from another.
1396 * Copy the current, root, and jail root vnode references.
1399 fdinit(struct filedesc *fdp)
1401 struct filedesc0 *newfdp;
1403 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1404 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1407 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1408 if (newfdp->fd_fd.fd_cdir)
1409 VREF(newfdp->fd_fd.fd_cdir);
1410 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1411 if (newfdp->fd_fd.fd_rdir)
1412 VREF(newfdp->fd_fd.fd_rdir);
1413 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1414 if (newfdp->fd_fd.fd_jdir)
1415 VREF(newfdp->fd_fd.fd_jdir);
1416 FILEDESC_UNLOCK(fdp);
1419 /* Create the file descriptor table. */
1420 newfdp->fd_fd.fd_refcnt = 1;
1421 newfdp->fd_fd.fd_holdcnt = 1;
1422 newfdp->fd_fd.fd_cmask = CMASK;
1423 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1424 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1425 newfdp->fd_fd.fd_nfiles = NDFILE;
1426 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1427 newfdp->fd_fd.fd_lastfile = -1;
1428 return (&newfdp->fd_fd);
1431 static struct filedesc *
1432 fdhold(struct proc *p)
1434 struct filedesc *fdp;
1436 mtx_lock(&fdesc_mtx);
1440 mtx_unlock(&fdesc_mtx);
1445 fddrop(struct filedesc *fdp)
1449 mtx_lock(&fdesc_mtx);
1450 i = --fdp->fd_holdcnt;
1451 mtx_unlock(&fdesc_mtx);
1455 mtx_destroy(&fdp->fd_mtx);
1456 FREE(fdp, M_FILEDESC);
1460 * Share a filedesc structure.
1463 fdshare(struct filedesc *fdp)
1465 FILEDESC_LOCK_FAST(fdp);
1467 FILEDESC_UNLOCK_FAST(fdp);
1472 * Unshare a filedesc structure, if necessary by making a copy
1475 fdunshare(struct proc *p, struct thread *td)
1478 FILEDESC_LOCK_FAST(p->p_fd);
1479 if (p->p_fd->fd_refcnt > 1) {
1480 struct filedesc *tmp;
1482 FILEDESC_UNLOCK_FAST(p->p_fd);
1483 tmp = fdcopy(p->p_fd);
1487 FILEDESC_UNLOCK_FAST(p->p_fd);
1491 * Copy a filedesc structure.
1492 * A NULL pointer in returns a NULL reference, this is to ease callers,
1496 fdcopy(struct filedesc *fdp)
1498 struct filedesc *newfdp;
1501 /* Certain daemons might not have file descriptors. */
1505 newfdp = fdinit(fdp);
1506 FILEDESC_LOCK_FAST(fdp);
1507 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1508 FILEDESC_UNLOCK_FAST(fdp);
1509 FILEDESC_LOCK(newfdp);
1510 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1511 FILEDESC_UNLOCK(newfdp);
1512 FILEDESC_LOCK_FAST(fdp);
1514 /* copy everything except kqueue descriptors */
1515 newfdp->fd_freefile = -1;
1516 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1517 if (fdisused(fdp, i) &&
1518 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1519 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1520 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1521 fhold(newfdp->fd_ofiles[i]);
1522 newfdp->fd_lastfile = i;
1524 if (newfdp->fd_freefile == -1)
1525 newfdp->fd_freefile = i;
1528 FILEDESC_UNLOCK_FAST(fdp);
1529 FILEDESC_LOCK(newfdp);
1530 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1531 if (newfdp->fd_ofiles[i] != NULL)
1533 FILEDESC_UNLOCK(newfdp);
1534 FILEDESC_LOCK_FAST(fdp);
1535 if (newfdp->fd_freefile == -1)
1536 newfdp->fd_freefile = i;
1537 newfdp->fd_cmask = fdp->fd_cmask;
1538 FILEDESC_UNLOCK_FAST(fdp);
1543 * Release a filedesc structure.
1546 fdfree(struct thread *td)
1548 struct filedesc *fdp;
1551 struct filedesc_to_leader *fdtol;
1553 struct vnode *cdir, *jdir, *rdir, *vp;
1556 /* Certain daemons might not have file descriptors. */
1557 fdp = td->td_proc->p_fd;
1561 /* Check for special need to clear POSIX style locks */
1562 fdtol = td->td_proc->p_fdtol;
1563 if (fdtol != NULL) {
1565 KASSERT(fdtol->fdl_refcount > 0,
1566 ("filedesc_to_refcount botch: fdl_refcount=%d",
1567 fdtol->fdl_refcount));
1568 if (fdtol->fdl_refcount == 1 &&
1569 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1570 for (i = 0, fpp = fdp->fd_ofiles;
1571 i <= fdp->fd_lastfile;
1574 (*fpp)->f_type != DTYPE_VNODE)
1578 FILEDESC_UNLOCK(fdp);
1579 lf.l_whence = SEEK_SET;
1582 lf.l_type = F_UNLCK;
1584 locked = VFS_LOCK_GIANT(vp->v_mount);
1585 (void) VOP_ADVLOCK(vp,
1586 (caddr_t)td->td_proc->
1591 VFS_UNLOCK_GIANT(locked);
1594 fpp = fdp->fd_ofiles + i;
1598 if (fdtol->fdl_refcount == 1) {
1599 if (fdp->fd_holdleaderscount > 0 &&
1600 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1602 * close() or do_dup() has cleared a reference
1603 * in a shared file descriptor table.
1605 fdp->fd_holdleaderswakeup = 1;
1606 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1607 PLOCK, "fdlhold", 0);
1610 if (fdtol->fdl_holdcount > 0) {
1612 * Ensure that fdtol->fdl_leader
1613 * remains valid in closef().
1615 fdtol->fdl_wakeup = 1;
1616 msleep(fdtol, &fdp->fd_mtx,
1617 PLOCK, "fdlhold", 0);
1621 fdtol->fdl_refcount--;
1622 if (fdtol->fdl_refcount == 0 &&
1623 fdtol->fdl_holdcount == 0) {
1624 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1625 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1628 td->td_proc->p_fdtol = NULL;
1629 FILEDESC_UNLOCK(fdp);
1631 FREE(fdtol, M_FILEDESC_TO_LEADER);
1633 FILEDESC_LOCK_FAST(fdp);
1634 i = --fdp->fd_refcnt;
1635 FILEDESC_UNLOCK_FAST(fdp);
1639 * We are the last reference to the structure, so we can
1640 * safely assume it will not change out from under us.
1642 fpp = fdp->fd_ofiles;
1643 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1645 (void) closef(*fpp, td);
1649 /* XXX This should happen earlier. */
1650 mtx_lock(&fdesc_mtx);
1651 td->td_proc->p_fd = NULL;
1652 mtx_unlock(&fdesc_mtx);
1654 if (fdp->fd_nfiles > NDFILE)
1655 FREE(fdp->fd_ofiles, M_FILEDESC);
1656 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1657 FREE(fdp->fd_map, M_FILEDESC);
1661 cdir = fdp->fd_cdir;
1662 fdp->fd_cdir = NULL;
1663 rdir = fdp->fd_rdir;
1664 fdp->fd_rdir = NULL;
1665 jdir = fdp->fd_jdir;
1666 fdp->fd_jdir = NULL;
1667 FILEDESC_UNLOCK(fdp);
1670 locked = VFS_LOCK_GIANT(cdir->v_mount);
1672 VFS_UNLOCK_GIANT(locked);
1675 locked = VFS_LOCK_GIANT(rdir->v_mount);
1677 VFS_UNLOCK_GIANT(locked);
1680 locked = VFS_LOCK_GIANT(jdir->v_mount);
1682 VFS_UNLOCK_GIANT(locked);
1689 * For setugid programs, we don't want to people to use that setugidness
1690 * to generate error messages which write to a file which otherwise would
1691 * otherwise be off-limits to the process. We check for filesystems where
1692 * the vnode can change out from under us after execve (like [lin]procfs).
1694 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1695 * sufficient. We also don't check for setugidness since we know we are.
1698 is_unsafe(struct file *fp)
1700 if (fp->f_type == DTYPE_VNODE) {
1701 struct vnode *vp = fp->f_vnode;
1703 if ((vp->v_vflag & VV_PROCDEP) != 0)
1710 * Make this setguid thing safe, if at all possible.
1713 setugidsafety(struct thread *td)
1715 struct filedesc *fdp;
1718 /* Certain daemons might not have file descriptors. */
1719 fdp = td->td_proc->p_fd;
1724 * Note: fdp->fd_ofiles may be reallocated out from under us while
1725 * we are blocked in a close. Be careful!
1728 for (i = 0; i <= fdp->fd_lastfile; i++) {
1731 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1734 knote_fdclose(td, i);
1736 * NULL-out descriptor prior to close to avoid
1737 * a race while close blocks.
1739 fp = fdp->fd_ofiles[i];
1740 fdp->fd_ofiles[i] = NULL;
1741 fdp->fd_ofileflags[i] = 0;
1743 FILEDESC_UNLOCK(fdp);
1744 (void) closef(fp, td);
1748 FILEDESC_UNLOCK(fdp);
1752 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1756 if (fdp->fd_ofiles[idx] == fp) {
1757 fdp->fd_ofiles[idx] = NULL;
1759 FILEDESC_UNLOCK(fdp);
1762 FILEDESC_UNLOCK(fdp);
1767 * Close any files on exec?
1770 fdcloseexec(struct thread *td)
1772 struct filedesc *fdp;
1775 /* Certain daemons might not have file descriptors. */
1776 fdp = td->td_proc->p_fd;
1783 * We cannot cache fd_ofiles or fd_ofileflags since operations
1784 * may block and rip them out from under us.
1786 for (i = 0; i <= fdp->fd_lastfile; i++) {
1787 if (fdp->fd_ofiles[i] != NULL &&
1788 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1789 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1792 knote_fdclose(td, i);
1794 * NULL-out descriptor prior to close to avoid
1795 * a race while close blocks.
1797 fp = fdp->fd_ofiles[i];
1798 fdp->fd_ofiles[i] = NULL;
1799 fdp->fd_ofileflags[i] = 0;
1801 if (fp->f_type == DTYPE_MQUEUE)
1802 mq_fdclose(td, i, fp);
1803 FILEDESC_UNLOCK(fdp);
1804 (void) closef(fp, td);
1808 FILEDESC_UNLOCK(fdp);
1812 * It is unsafe for set[ug]id processes to be started with file
1813 * descriptors 0..2 closed, as these descriptors are given implicit
1814 * significance in the Standard C library. fdcheckstd() will create a
1815 * descriptor referencing /dev/null for each of stdin, stdout, and
1816 * stderr that is not already open.
1819 fdcheckstd(struct thread *td)
1821 struct nameidata nd;
1822 struct filedesc *fdp;
1825 int fd, i, error, flags, devnull;
1827 fdp = td->td_proc->p_fd;
1830 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1833 for (i = 0; i < 3; i++) {
1834 if (fdp->fd_ofiles[i] != NULL)
1838 error = falloc(td, &fp, &fd);
1841 /* Note extra ref on `fp' held for us by falloc(). */
1842 KASSERT(fd == i, ("oof, we didn't get our fd"));
1843 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1845 flags = FREAD | FWRITE;
1846 error = vn_open(&nd, &flags, 0, fd);
1849 * Someone may have closed the entry in the
1850 * file descriptor table, so check it hasn't
1851 * changed before dropping the reference count.
1854 KASSERT(fdp->fd_ofiles[fd] == fp,
1855 ("table not shared, how did it change?"));
1856 fdp->fd_ofiles[fd] = NULL;
1858 FILEDESC_UNLOCK(fdp);
1863 vfslocked = NDHASGIANT(&nd);
1864 NDFREE(&nd, NDF_ONLY_PNBUF);
1866 fp->f_vnode = nd.ni_vp;
1867 if (fp->f_data == NULL)
1868 fp->f_data = nd.ni_vp;
1869 if (fp->f_ops == &badfileops)
1871 fp->f_type = DTYPE_VNODE;
1872 VOP_UNLOCK(nd.ni_vp, 0, td);
1873 VFS_UNLOCK_GIANT(vfslocked);
1877 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1886 * Internal form of close.
1887 * Decrement reference count on file structure.
1888 * Note: td may be NULL when closing a file that was being passed in a
1891 * XXXRW: Giant is not required for the caller, but often will be held; this
1892 * makes it moderately likely the Giant will be recursed in the VFS case.
1895 closef(struct file *fp, struct thread *td)
1899 struct filedesc_to_leader *fdtol;
1900 struct filedesc *fdp;
1903 * POSIX record locking dictates that any close releases ALL
1904 * locks owned by this process. This is handled by setting
1905 * a flag in the unlock to free ONLY locks obeying POSIX
1906 * semantics, and not to free BSD-style file locks.
1907 * If the descriptor was in a message, POSIX-style locks
1908 * aren't passed with the descriptor, and the thread pointer
1909 * will be NULL. Callers should be careful only to pass a
1910 * NULL thread pointer when there really is no owning
1911 * context that might have locks, or the locks will be
1914 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1918 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1919 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1920 lf.l_whence = SEEK_SET;
1923 lf.l_type = F_UNLCK;
1924 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1925 F_UNLCK, &lf, F_POSIX);
1927 fdtol = td->td_proc->p_fdtol;
1928 if (fdtol != NULL) {
1930 * Handle special case where file descriptor table
1931 * is shared between multiple process leaders.
1933 fdp = td->td_proc->p_fd;
1935 for (fdtol = fdtol->fdl_next;
1936 fdtol != td->td_proc->p_fdtol;
1937 fdtol = fdtol->fdl_next) {
1938 if ((fdtol->fdl_leader->p_flag &
1941 fdtol->fdl_holdcount++;
1942 FILEDESC_UNLOCK(fdp);
1943 lf.l_whence = SEEK_SET;
1946 lf.l_type = F_UNLCK;
1948 (void) VOP_ADVLOCK(vp,
1949 (caddr_t)fdtol->fdl_leader,
1950 F_UNLCK, &lf, F_POSIX);
1952 fdtol->fdl_holdcount--;
1953 if (fdtol->fdl_holdcount == 0 &&
1954 fdtol->fdl_wakeup != 0) {
1955 fdtol->fdl_wakeup = 0;
1959 FILEDESC_UNLOCK(fdp);
1961 VFS_UNLOCK_GIANT(vfslocked);
1963 return (fdrop(fp, td));
1967 * Extract the file pointer associated with the specified descriptor for
1968 * the current user process.
1970 * If the descriptor doesn't exist, EBADF is returned.
1972 * If the descriptor exists but doesn't match 'flags' then
1973 * return EBADF for read attempts and EINVAL for write attempts.
1975 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1976 * It should be dropped with fdrop().
1977 * If it is not set, then the refcount will not be bumped however the
1978 * thread's filedesc struct will be returned locked (for fgetsock).
1980 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1981 * Otherwise *fpp is set and zero is returned.
1984 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1986 struct filedesc *fdp;
1990 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1993 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1994 FILEDESC_UNLOCK(fdp);
1999 * FREAD and FWRITE failure return EBADF as per POSIX.
2001 * Only one flag, or 0, may be specified.
2003 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
2004 FILEDESC_UNLOCK(fdp);
2007 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2008 FILEDESC_UNLOCK(fdp);
2013 FILEDESC_UNLOCK(fdp);
2020 fget(struct thread *td, int fd, struct file **fpp)
2023 return(_fget(td, fd, fpp, 0, 1));
2027 fget_read(struct thread *td, int fd, struct file **fpp)
2030 return(_fget(td, fd, fpp, FREAD, 1));
2034 fget_write(struct thread *td, int fd, struct file **fpp)
2037 return(_fget(td, fd, fpp, FWRITE, 1));
2041 * Like fget() but loads the underlying vnode, or returns an error if
2042 * the descriptor does not represent a vnode. Note that pipes use vnodes
2043 * but never have VM objects. The returned vnode will be vref()d.
2045 * XXX: what about the unused flags ?
2048 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2054 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2056 if (fp->f_vnode == NULL) {
2062 FILEDESC_UNLOCK(td->td_proc->p_fd);
2067 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2070 return (_fgetvp(td, fd, vpp, 0));
2074 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2077 return (_fgetvp(td, fd, vpp, FREAD));
2082 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2085 return (_fgetvp(td, fd, vpp, FWRITE));
2090 * Like fget() but loads the underlying socket, or returns an error if
2091 * the descriptor does not represent a socket.
2093 * We bump the ref count on the returned socket. XXX Also obtain the SX
2094 * lock in the future.
2096 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2097 * on their file descriptor reference to prevent the socket from being
2101 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2111 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2113 if (fp->f_type != DTYPE_SOCKET) {
2118 *fflagp = fp->f_flag;
2123 FILEDESC_UNLOCK(td->td_proc->p_fd);
2128 * Drop the reference count on the socket and XXX release the SX lock in the
2129 * future. The last reference closes the socket.
2131 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2134 fputsock(struct socket *so)
2144 fdrop(struct file *fp, struct thread *td)
2148 return (fdrop_locked(fp, td));
2152 * Drop reference on struct file passed in, may call closef if the
2153 * reference hits zero.
2154 * Expects struct file locked, and will unlock it.
2157 fdrop_locked(struct file *fp, struct thread *td)
2161 FILE_LOCK_ASSERT(fp, MA_OWNED);
2163 if (--fp->f_count > 0) {
2167 /* We have the last ref so we can proceed without the file lock. */
2169 if (fp->f_count < 0)
2170 panic("fdrop: count < 0");
2171 if (fp->f_ops != &badfileops)
2172 error = fo_close(fp, td);
2176 sx_xlock(&filelist_lock);
2177 LIST_REMOVE(fp, f_list);
2179 sx_xunlock(&filelist_lock);
2181 uma_zfree(file_zone, fp);
2187 * Apply an advisory lock on a file descriptor.
2189 * Just attempt to get a record lock of the requested type on
2190 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2192 #ifndef _SYS_SYSPROTO_H_
2203 flock(struct thread *td, struct flock_args *uap)
2210 if ((error = fget(td, uap->fd, &fp)) != 0)
2212 if (fp->f_type != DTYPE_VNODE) {
2214 return (EOPNOTSUPP);
2219 lf.l_whence = SEEK_SET;
2222 if (uap->how & LOCK_UN) {
2223 lf.l_type = F_UNLCK;
2225 fp->f_flag &= ~FHASLOCK;
2227 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2230 if (uap->how & LOCK_EX)
2231 lf.l_type = F_WRLCK;
2232 else if (uap->how & LOCK_SH)
2233 lf.l_type = F_RDLCK;
2239 fp->f_flag |= FHASLOCK;
2241 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2242 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2249 * Duplicate the specified descriptor to a free descriptor.
2252 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2258 * If the to-be-dup'd fd number is greater than the allowed number
2259 * of file descriptors, or the fd to be dup'd has already been
2260 * closed, then reject.
2263 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2264 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2265 FILEDESC_UNLOCK(fdp);
2270 * There are two cases of interest here.
2272 * For ENODEV simply dup (dfd) to file descriptor
2273 * (indx) and return.
2275 * For ENXIO steal away the file structure from (dfd) and
2276 * store it in (indx). (dfd) is effectively closed by
2279 * Any other error code is just returned.
2284 * Check that the mode the file is being opened for is a
2285 * subset of the mode of the existing descriptor.
2288 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2290 FILEDESC_UNLOCK(fdp);
2293 fp = fdp->fd_ofiles[indx];
2294 fdp->fd_ofiles[indx] = wfp;
2295 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2300 FILEDESC_UNLOCK(fdp);
2303 * We now own the reference to fp that the ofiles[]
2304 * array used to own. Release it.
2307 fdrop_locked(fp, td);
2313 * Steal away the file pointer from dfd and stuff it into indx.
2315 fp = fdp->fd_ofiles[indx];
2316 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2317 fdp->fd_ofiles[dfd] = NULL;
2318 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2319 fdp->fd_ofileflags[dfd] = 0;
2327 * We now own the reference to fp that the ofiles[] array
2328 * used to own. Release it.
2331 fdrop_locked(fp, td);
2333 FILEDESC_UNLOCK(fdp);
2338 FILEDESC_UNLOCK(fdp);
2345 * Scan all active processes to see if any of them have a current
2346 * or root directory of `olddp'. If so, replace them with the new
2350 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2352 struct filedesc *fdp;
2356 if (vrefcnt(olddp) == 1)
2358 sx_slock(&allproc_lock);
2359 LIST_FOREACH(p, &allproc, p_list) {
2364 FILEDESC_LOCK_FAST(fdp);
2365 if (fdp->fd_cdir == olddp) {
2367 fdp->fd_cdir = newdp;
2370 if (fdp->fd_rdir == olddp) {
2372 fdp->fd_rdir = newdp;
2375 FILEDESC_UNLOCK_FAST(fdp);
2380 sx_sunlock(&allproc_lock);
2381 if (rootvnode == olddp) {
2388 struct filedesc_to_leader *
2389 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2391 struct filedesc_to_leader *fdtol;
2393 MALLOC(fdtol, struct filedesc_to_leader *,
2394 sizeof(struct filedesc_to_leader),
2395 M_FILEDESC_TO_LEADER,
2397 fdtol->fdl_refcount = 1;
2398 fdtol->fdl_holdcount = 0;
2399 fdtol->fdl_wakeup = 0;
2400 fdtol->fdl_leader = leader;
2403 fdtol->fdl_next = old->fdl_next;
2404 fdtol->fdl_prev = old;
2405 old->fdl_next = fdtol;
2406 fdtol->fdl_next->fdl_prev = fdtol;
2407 FILEDESC_UNLOCK(fdp);
2409 fdtol->fdl_next = fdtol;
2410 fdtol->fdl_prev = fdtol;
2416 * Get file structures.
2419 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2422 struct filedesc *fdp;
2428 * Note: because the number of file descriptors is calculated
2429 * in different ways for sizing vs returning the data,
2430 * there is information leakage from the first loop. However,
2431 * it is of a similar order of magnitude to the leakage from
2432 * global system statistics such as kern.openfiles.
2434 error = sysctl_wire_old_buffer(req, 0);
2437 if (req->oldptr == NULL) {
2438 n = 16; /* A slight overestimate. */
2439 sx_slock(&filelist_lock);
2440 LIST_FOREACH(fp, &filehead, f_list) {
2442 * We should grab the lock, but this is an
2443 * estimate, so does it really matter?
2445 /* mtx_lock(fp->f_mtxp); */
2447 /* mtx_unlock(f->f_mtxp); */
2449 sx_sunlock(&filelist_lock);
2450 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2453 bzero(&xf, sizeof(xf));
2454 xf.xf_size = sizeof(xf);
2455 sx_slock(&allproc_lock);
2456 LIST_FOREACH(p, &allproc, p_list) {
2457 if (p->p_state == PRS_NEW)
2460 if (p_cansee(req->td, p) != 0) {
2464 xf.xf_pid = p->p_pid;
2465 xf.xf_uid = p->p_ucred->cr_uid;
2470 FILEDESC_LOCK_FAST(fdp);
2471 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2472 if ((fp = fdp->fd_ofiles[n]) == NULL)
2476 xf.xf_data = fp->f_data;
2477 xf.xf_vnode = fp->f_vnode;
2478 xf.xf_type = fp->f_type;
2479 xf.xf_count = fp->f_count;
2480 xf.xf_msgcount = fp->f_msgcount;
2481 xf.xf_offset = fp->f_offset;
2482 xf.xf_flag = fp->f_flag;
2483 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2487 FILEDESC_UNLOCK_FAST(fdp);
2492 sx_sunlock(&allproc_lock);
2496 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2497 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2501 * For the purposes of debugging, generate a human-readable string for the
2505 file_type_to_name(short type)
2527 * For the purposes of debugging, identify a process (if any, perhaps one of
2528 * many) that references the passed file in its file descriptor array. Return
2531 static struct proc *
2532 file_to_first_proc(struct file *fp)
2534 struct filedesc *fdp;
2538 LIST_FOREACH(p, &allproc, p_list) {
2539 if (p->p_state == PRS_NEW)
2544 for (n = 0; n < fdp->fd_nfiles; n++) {
2545 if (fp == fdp->fd_ofiles[n])
2552 DB_SHOW_COMMAND(files, db_show_files)
2557 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
2558 "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
2560 LIST_FOREACH(fp, &filehead, f_list) {
2561 p = file_to_first_proc(fp);
2562 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2563 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2564 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2565 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2570 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2571 &maxfilesperproc, 0, "Maximum files allowed open per process");
2573 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2574 &maxfiles, 0, "Maximum number of files");
2576 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2577 &openfiles, 0, "System-wide number of open files");
2581 filelistinit(void *dummy)
2584 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2585 NULL, NULL, UMA_ALIGN_PTR, 0);
2586 sx_init(&filelist_lock, "filelist lock");
2587 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2588 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2590 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2592 /*-------------------------------------------------------------------*/
2595 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2602 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2609 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2616 badfo_kqfilter(struct file *fp, struct knote *kn)
2623 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2630 badfo_close(struct file *fp, struct thread *td)
2636 struct fileops badfileops = {
2637 .fo_read = badfo_readwrite,
2638 .fo_write = badfo_readwrite,
2639 .fo_ioctl = badfo_ioctl,
2640 .fo_poll = badfo_poll,
2641 .fo_kqfilter = badfo_kqfilter,
2642 .fo_stat = badfo_stat,
2643 .fo_close = badfo_close,
2647 /*-------------------------------------------------------------------*/
2650 * File Descriptor pseudo-device driver (/dev/fd/).
2652 * Opening minor device N dup()s the file (if any) connected to file
2653 * descriptor N belonging to the calling process. Note that this driver
2654 * consists of only the ``open()'' routine, because all subsequent
2655 * references to this file will be direct to the other driver.
2657 * XXX: we could give this one a cloning event handler if necessary.
2662 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2666 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2667 * the file descriptor being sought for duplication. The error
2668 * return ensures that the vnode for this device will be released
2669 * by vn_open. Open will detect this special error and take the
2670 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2671 * will simply report the error.
2673 td->td_dupfd = dev2unit(dev);
2677 static struct cdevsw fildesc_cdevsw = {
2678 .d_version = D_VERSION,
2679 .d_flags = D_NEEDGIANT,
2685 fildesc_drvinit(void *unused)
2689 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2690 make_dev_alias(dev, "stdin");
2691 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2692 make_dev_alias(dev, "stdout");
2693 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2694 make_dev_alias(dev, "stderr");
2697 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)