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>
62 #include <sys/resourcevar.h>
63 #include <sys/signalvar.h>
64 #include <sys/socketvar.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
70 #include <sys/unistd.h>
71 #include <sys/vnode.h>
73 #include <security/audit/audit.h>
79 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
80 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
81 "file desc to leader structures");
82 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
84 static uma_zone_t file_zone;
87 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
88 enum dup_type { DUP_VARIABLE, DUP_FIXED };
90 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
92 static int fd_first_free(struct filedesc *, int, int);
93 static int fd_last_used(struct filedesc *, int, int);
94 static void fdgrowtable(struct filedesc *, int);
95 static int fdrop_locked(struct file *fp, struct thread *td);
96 static void fdunused(struct filedesc *fdp, int fd);
97 static void fdused(struct filedesc *fdp, int fd);
100 * A process is initially started out with NDFILE descriptors stored within
101 * this structure, selected to be enough for typical applications based on
102 * the historical limit of 20 open files (and the usage of descriptors by
103 * shells). If these descriptors are exhausted, a larger descriptor table
104 * may be allocated, up to a process' resource limit; the internal arrays
108 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
109 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
110 #define NDSLOT(x) ((x) / NDENTRIES)
111 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
112 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
115 * Storage required per open file descriptor.
117 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
120 * Basic allocation of descriptors:
121 * one of the above, plus arrays for NDFILE descriptors.
124 struct filedesc fd_fd;
126 * These arrays are used when the number of open files is
127 * <= NDFILE, and are then pointed to by the pointers above.
129 struct file *fd_dfiles[NDFILE];
130 char fd_dfileflags[NDFILE];
131 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
135 * Descriptor management.
137 struct filelist filehead; /* head of list of open files */
138 int openfiles; /* actual number of open files */
139 struct sx filelist_lock; /* sx to protect filelist */
140 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
141 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
143 /* A mutex to protect the association between a proc and filedesc. */
144 static struct mtx fdesc_mtx;
147 * Find the first zero bit in the given bitmap, starting at low and not
148 * exceeding size - 1.
151 fd_first_free(struct filedesc *fdp, int low, int size)
153 NDSLOTTYPE *map = fdp->fd_map;
161 if (low % NDENTRIES) {
162 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
163 if ((mask &= ~map[off]) != 0UL)
164 return (off * NDENTRIES + ffsl(mask) - 1);
167 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
168 if (map[off] != ~0UL)
169 return (off * NDENTRIES + ffsl(~map[off]) - 1);
174 * Find the highest non-zero bit in the given bitmap, starting at low and
175 * not exceeding size - 1.
178 fd_last_used(struct filedesc *fdp, int low, int size)
180 NDSLOTTYPE *map = fdp->fd_map;
188 if (size % NDENTRIES) {
189 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
190 if ((mask &= map[off]) != 0)
191 return (off * NDENTRIES + flsl(mask) - 1);
194 for (minoff = NDSLOT(low); off >= minoff; --off)
196 return (off * NDENTRIES + flsl(map[off]) - 1);
201 fdisused(struct filedesc *fdp, int fd)
203 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
204 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
205 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
209 * Mark a file descriptor as used.
212 fdused(struct filedesc *fdp, int fd)
214 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
215 KASSERT(!fdisused(fdp, fd),
216 ("fd already used"));
217 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
218 if (fd > fdp->fd_lastfile)
219 fdp->fd_lastfile = fd;
220 if (fd == fdp->fd_freefile)
221 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
225 * Mark a file descriptor as unused.
228 fdunused(struct filedesc *fdp, int fd)
230 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
231 KASSERT(fdisused(fdp, fd),
232 ("fd is already unused"));
233 KASSERT(fdp->fd_ofiles[fd] == NULL,
234 ("fd is still in use"));
235 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
236 if (fd < fdp->fd_freefile)
237 fdp->fd_freefile = fd;
238 if (fd == fdp->fd_lastfile)
239 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
243 * System calls on descriptors.
245 #ifndef _SYS_SYSPROTO_H_
246 struct getdtablesize_args {
255 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
257 struct proc *p = td->td_proc;
261 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
267 * Duplicate a file descriptor to a particular value.
269 * note: keep in mind that a potential race condition exists when closing
270 * descriptors from a shared descriptor table (via rfork).
272 #ifndef _SYS_SYSPROTO_H_
283 dup2(struct thread *td, struct dup2_args *uap)
286 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
291 * Duplicate a file descriptor.
293 #ifndef _SYS_SYSPROTO_H_
303 dup(struct thread *td, struct dup_args *uap)
306 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
310 * The file control system call.
312 #ifndef _SYS_SYSPROTO_H_
324 fcntl(struct thread *td, struct fcntl_args *uap)
335 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
344 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
347 if (uap->cmd == F_GETLK)
348 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
353 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
355 struct filedesc *fdp;
366 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
367 * avoid grabbing Giant for calls we know don't need it.
387 if ((unsigned)fd >= fdp->fd_nfiles ||
388 (fp = fdp->fd_ofiles[fd]) == NULL) {
389 FILEDESC_UNLOCK(fdp);
393 pop = &fdp->fd_ofileflags[fd];
397 /* mtx_assert(&Giant, MA_NOTOWNED); */
398 FILEDESC_UNLOCK(fdp);
401 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
402 newmin >= maxfilesperproc) {
408 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
412 /* mtx_assert(&Giant, MA_NOTOWNED); */
413 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
414 FILEDESC_UNLOCK(fdp);
418 /* mtx_assert(&Giant, MA_NOTOWNED); */
419 *pop = (*pop &~ UF_EXCLOSE) |
420 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
421 FILEDESC_UNLOCK(fdp);
425 /* mtx_assert(&Giant, MA_NOTOWNED); */
427 td->td_retval[0] = OFLAGS(fp->f_flag);
429 FILEDESC_UNLOCK(fdp);
433 mtx_assert(&Giant, MA_OWNED);
436 fp->f_flag &= ~FCNTLFLAGS;
437 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
439 FILEDESC_UNLOCK(fdp);
440 tmp = fp->f_flag & FNONBLOCK;
441 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
446 tmp = fp->f_flag & FASYNC;
447 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
453 fp->f_flag &= ~FNONBLOCK;
456 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
461 mtx_assert(&Giant, MA_OWNED);
463 FILEDESC_UNLOCK(fdp);
464 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
466 td->td_retval[0] = tmp;
471 mtx_assert(&Giant, MA_OWNED);
473 FILEDESC_UNLOCK(fdp);
475 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
480 mtx_assert(&Giant, MA_OWNED);
482 /* FALLTHROUGH F_SETLK */
485 mtx_assert(&Giant, MA_OWNED);
486 if (fp->f_type != DTYPE_VNODE) {
487 FILEDESC_UNLOCK(fdp);
492 flp = (struct flock *)arg;
493 if (flp->l_whence == SEEK_CUR) {
494 if (fp->f_offset < 0 ||
496 fp->f_offset > OFF_MAX - flp->l_start)) {
497 FILEDESC_UNLOCK(fdp);
501 flp->l_start += fp->f_offset;
505 * VOP_ADVLOCK() may block.
508 FILEDESC_UNLOCK(fdp);
511 switch (flp->l_type) {
513 if ((fp->f_flag & FREAD) == 0) {
517 PROC_LOCK(p->p_leader);
518 p->p_leader->p_flag |= P_ADVLOCK;
519 PROC_UNLOCK(p->p_leader);
520 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
524 if ((fp->f_flag & FWRITE) == 0) {
528 PROC_LOCK(p->p_leader);
529 p->p_leader->p_flag |= P_ADVLOCK;
530 PROC_UNLOCK(p->p_leader);
531 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
535 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
542 /* Check for race with close */
543 FILEDESC_LOCK_FAST(fdp);
544 if ((unsigned) fd >= fdp->fd_nfiles ||
545 fp != fdp->fd_ofiles[fd]) {
546 FILEDESC_UNLOCK_FAST(fdp);
547 flp->l_whence = SEEK_SET;
550 flp->l_type = F_UNLCK;
551 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
552 F_UNLCK, flp, F_POSIX);
554 FILEDESC_UNLOCK_FAST(fdp);
559 mtx_assert(&Giant, MA_OWNED);
560 if (fp->f_type != DTYPE_VNODE) {
561 FILEDESC_UNLOCK(fdp);
565 flp = (struct flock *)arg;
566 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
567 flp->l_type != F_UNLCK) {
568 FILEDESC_UNLOCK(fdp);
572 if (flp->l_whence == SEEK_CUR) {
573 if ((flp->l_start > 0 &&
574 fp->f_offset > OFF_MAX - flp->l_start) ||
576 fp->f_offset < OFF_MIN - flp->l_start)) {
577 FILEDESC_UNLOCK(fdp);
581 flp->l_start += fp->f_offset;
584 * VOP_ADVLOCK() may block.
587 FILEDESC_UNLOCK(fdp);
589 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
594 FILEDESC_UNLOCK(fdp);
605 * Common code for dup, dup2, and fcntl(F_DUPFD).
608 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
610 struct filedesc *fdp;
614 int error, holdleaders, maxfd;
616 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
617 ("invalid dup type %d", type));
623 * Verify we have a valid descriptor to dup from and possibly to
626 if (old < 0 || new < 0)
629 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
635 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
636 FILEDESC_UNLOCK(fdp);
639 if (type == DUP_FIXED && old == new) {
641 FILEDESC_UNLOCK(fdp);
644 fp = fdp->fd_ofiles[old];
648 * If the caller specified a file descriptor, make sure the file
649 * table is large enough to hold it, and grab it. Otherwise, just
650 * allocate a new descriptor the usual way. Since the filedesc
651 * lock may be temporarily dropped in the process, we have to look
654 if (type == DUP_FIXED) {
655 if (new >= fdp->fd_nfiles)
656 fdgrowtable(fdp, new + 1);
657 if (fdp->fd_ofiles[new] == NULL)
660 if ((error = fdalloc(td, new, &new)) != 0) {
661 FILEDESC_UNLOCK(fdp);
668 * If the old file changed out from under us then treat it as a
669 * bad file descriptor. Userland should do its own locking to
672 if (fdp->fd_ofiles[old] != fp) {
673 /* we've allocated a descriptor which we won't use */
674 if (fdp->fd_ofiles[new] == NULL)
676 FILEDESC_UNLOCK(fdp);
681 ("new fd is same as old"));
684 * Save info on the descriptor being overwritten. We cannot close
685 * it without introducing an ownership race for the slot, since we
686 * need to drop the filedesc lock to call closef().
688 * XXX this duplicates parts of close().
690 delfp = fdp->fd_ofiles[new];
693 if (td->td_proc->p_fdtol != NULL) {
695 * Ask fdfree() to sleep to ensure that all relevant
696 * process leaders can be traversed in closef().
698 fdp->fd_holdleaderscount++;
704 * Duplicate the source descriptor
706 fdp->fd_ofiles[new] = fp;
707 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
708 if (new > fdp->fd_lastfile)
709 fdp->fd_lastfile = new;
713 * If we dup'd over a valid file, we now own the reference to it
714 * and must dispose of it using closef() semantics (as if a
715 * close() were performed on it).
717 * XXX this duplicates parts of close().
720 knote_fdclose(td, new);
721 if (delfp->f_type == DTYPE_MQUEUE)
722 mq_fdclose(td, new, delfp);
723 FILEDESC_UNLOCK(fdp);
724 (void) closef(delfp, td);
726 FILEDESC_LOCK_FAST(fdp);
727 fdp->fd_holdleaderscount--;
728 if (fdp->fd_holdleaderscount == 0 &&
729 fdp->fd_holdleaderswakeup != 0) {
730 fdp->fd_holdleaderswakeup = 0;
731 wakeup(&fdp->fd_holdleaderscount);
733 FILEDESC_UNLOCK_FAST(fdp);
736 FILEDESC_UNLOCK(fdp);
742 * If sigio is on the list associated with a process or process group,
743 * disable signalling from the device, remove sigio from the list and
747 funsetown(struct sigio **sigiop)
757 *(sigio->sio_myref) = NULL;
758 if ((sigio)->sio_pgid < 0) {
759 struct pgrp *pg = (sigio)->sio_pgrp;
761 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
765 struct proc *p = (sigio)->sio_proc;
767 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
772 crfree(sigio->sio_ucred);
773 FREE(sigio, M_SIGIO);
777 * Free a list of sigio structures.
778 * We only need to lock the SIGIO_LOCK because we have made ourselves
779 * inaccessible to callers of fsetown and therefore do not need to lock
780 * the proc or pgrp struct for the list manipulation.
783 funsetownlst(struct sigiolst *sigiolst)
789 sigio = SLIST_FIRST(sigiolst);
796 * Every entry of the list should belong
797 * to a single proc or pgrp.
799 if (sigio->sio_pgid < 0) {
800 pg = sigio->sio_pgrp;
801 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
802 } else /* if (sigio->sio_pgid > 0) */ {
804 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
808 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
809 *(sigio->sio_myref) = NULL;
811 KASSERT(sigio->sio_pgid < 0,
812 ("Proc sigio in pgrp sigio list"));
813 KASSERT(sigio->sio_pgrp == pg,
814 ("Bogus pgrp in sigio list"));
816 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
819 } else /* if (p != NULL) */ {
820 KASSERT(sigio->sio_pgid > 0,
821 ("Pgrp sigio in proc sigio list"));
822 KASSERT(sigio->sio_proc == p,
823 ("Bogus proc in sigio list"));
825 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
830 crfree(sigio->sio_ucred);
831 FREE(sigio, M_SIGIO);
838 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
840 * After permission checking, add a sigio structure to the sigio list for
841 * the process or process group.
844 fsetown(pid_t pgid, struct sigio **sigiop)
858 /* Allocate and fill in the new sigio out of locks. */
859 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
860 sigio->sio_pgid = pgid;
861 sigio->sio_ucred = crhold(curthread->td_ucred);
862 sigio->sio_myref = sigiop;
864 sx_slock(&proctree_lock);
873 * Policy - Don't allow a process to FSETOWN a process
874 * in another session.
876 * Remove this test to allow maximum flexibility or
877 * restrict FSETOWN to the current process or process
878 * group for maximum safety.
881 if (proc->p_session != curthread->td_proc->p_session) {
887 } else /* if (pgid < 0) */ {
888 pgrp = pgfind(-pgid);
896 * Policy - Don't allow a process to FSETOWN a process
897 * in another session.
899 * Remove this test to allow maximum flexibility or
900 * restrict FSETOWN to the current process or process
901 * group for maximum safety.
903 if (pgrp->pg_session != curthread->td_proc->p_session) {
914 * Since funsetownlst() is called without the proctree
915 * locked, we need to check for P_WEXIT.
916 * XXX: is ESRCH correct?
918 if ((proc->p_flag & P_WEXIT) != 0) {
923 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
924 sigio->sio_proc = proc;
928 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
929 sigio->sio_pgrp = pgrp;
932 sx_sunlock(&proctree_lock);
939 sx_sunlock(&proctree_lock);
940 crfree(sigio->sio_ucred);
941 FREE(sigio, M_SIGIO);
946 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
950 struct sigio **sigiop;
955 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
961 * Close a file descriptor.
963 #ifndef _SYS_SYSPROTO_H_
975 struct close_args *uap;
978 return (kern_close(td, uap->fd));
986 struct filedesc *fdp;
993 fdp = td->td_proc->p_fd;
995 AUDIT_SYSCLOSE(td, fd);
998 if ((unsigned)fd >= fdp->fd_nfiles ||
999 (fp = fdp->fd_ofiles[fd]) == NULL) {
1000 FILEDESC_UNLOCK(fdp);
1003 fdp->fd_ofiles[fd] = NULL;
1004 fdp->fd_ofileflags[fd] = 0;
1006 if (td->td_proc->p_fdtol != NULL) {
1008 * Ask fdfree() to sleep to ensure that all relevant
1009 * process leaders can be traversed in closef().
1011 fdp->fd_holdleaderscount++;
1016 * We now hold the fp reference that used to be owned by the descriptor
1018 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1019 * race of the fd getting opened, a knote added, and deleteing a knote
1022 knote_fdclose(td, fd);
1023 if (fp->f_type == DTYPE_MQUEUE)
1024 mq_fdclose(td, fd, fp);
1025 FILEDESC_UNLOCK(fdp);
1027 error = closef(fp, td);
1029 FILEDESC_LOCK_FAST(fdp);
1030 fdp->fd_holdleaderscount--;
1031 if (fdp->fd_holdleaderscount == 0 &&
1032 fdp->fd_holdleaderswakeup != 0) {
1033 fdp->fd_holdleaderswakeup = 0;
1034 wakeup(&fdp->fd_holdleaderscount);
1036 FILEDESC_UNLOCK_FAST(fdp);
1041 #if defined(COMPAT_43)
1043 * Return status information about a file descriptor.
1045 #ifndef _SYS_SYSPROTO_H_
1046 struct ofstat_args {
1056 ofstat(struct thread *td, struct ofstat_args *uap)
1062 error = kern_fstat(td, uap->fd, &ub);
1065 error = copyout(&oub, uap->sb, sizeof(oub));
1069 #endif /* COMPAT_43 */
1072 * Return status information about a file descriptor.
1074 #ifndef _SYS_SYSPROTO_H_
1085 fstat(struct thread *td, struct fstat_args *uap)
1090 error = kern_fstat(td, uap->fd, &ub);
1092 error = copyout(&ub, uap->sb, sizeof(ub));
1097 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1104 if ((error = fget(td, fd, &fp)) != 0)
1107 AUDIT_ARG(file, td->td_proc, fp);
1109 error = fo_stat(fp, sbp, td->td_ucred, td);
1115 * Return status information about a file descriptor.
1117 #ifndef _SYS_SYSPROTO_H_
1118 struct nfstat_args {
1128 nfstat(struct thread *td, struct nfstat_args *uap)
1134 error = kern_fstat(td, uap->fd, &ub);
1136 cvtnstat(&ub, &nub);
1137 error = copyout(&nub, uap->sb, sizeof(nub));
1143 * Return pathconf information about a file descriptor.
1145 #ifndef _SYS_SYSPROTO_H_
1146 struct fpathconf_args {
1156 fpathconf(struct thread *td, struct fpathconf_args *uap)
1162 if ((error = fget(td, uap->fd, &fp)) != 0)
1165 /* If asynchronous I/O is available, it works for all descriptors. */
1166 if (uap->name == _PC_ASYNC_IO) {
1167 td->td_retval[0] = async_io_version;
1173 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1174 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1175 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1176 VOP_UNLOCK(vp, 0, td);
1177 VFS_UNLOCK_GIANT(vfslocked);
1178 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1179 if (uap->name != _PC_PIPE_BUF) {
1182 td->td_retval[0] = PIPE_BUF;
1194 * Grow the file table to accomodate (at least) nfd descriptors. This may
1195 * block and drop the filedesc lock, but it will reacquire it before
1199 fdgrowtable(struct filedesc *fdp, int nfd)
1201 struct file **ntable;
1203 int nnfiles, onfiles;
1206 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1208 KASSERT(fdp->fd_nfiles > 0,
1209 ("zero-length file table"));
1211 /* compute the size of the new table */
1212 onfiles = fdp->fd_nfiles;
1213 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1214 if (nnfiles <= onfiles)
1215 /* the table is already large enough */
1218 /* allocate a new table and (if required) new bitmaps */
1219 FILEDESC_UNLOCK(fdp);
1220 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1221 M_FILEDESC, M_ZERO | M_WAITOK);
1222 nfileflags = (char *)&ntable[nnfiles];
1223 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1224 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1225 M_FILEDESC, M_ZERO | M_WAITOK);
1231 * We now have new tables ready to go. Since we dropped the
1232 * filedesc lock to call malloc(), watch out for a race.
1234 onfiles = fdp->fd_nfiles;
1235 if (onfiles >= nnfiles) {
1236 /* we lost the race, but that's OK */
1237 free(ntable, M_FILEDESC);
1239 free(nmap, M_FILEDESC);
1242 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1243 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1244 if (onfiles > NDFILE)
1245 free(fdp->fd_ofiles, M_FILEDESC);
1246 fdp->fd_ofiles = ntable;
1247 fdp->fd_ofileflags = nfileflags;
1248 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1249 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1250 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1251 free(fdp->fd_map, M_FILEDESC);
1254 fdp->fd_nfiles = nnfiles;
1258 * Allocate a file descriptor for the process.
1261 fdalloc(struct thread *td, int minfd, int *result)
1263 struct proc *p = td->td_proc;
1264 struct filedesc *fdp = p->p_fd;
1267 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1269 if (fdp->fd_freefile > minfd)
1270 minfd = fdp->fd_freefile;
1273 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1277 * Search the bitmap for a free descriptor. If none is found, try
1278 * to grow the file table. Keep at it until we either get a file
1279 * descriptor or run into process or system limits; fdgrowtable()
1280 * may drop the filedesc lock, so we're in a race.
1283 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1286 if (fd < fdp->fd_nfiles)
1288 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1292 * Perform some sanity checks, then mark the file descriptor as
1293 * used and return it to the caller.
1295 KASSERT(!fdisused(fdp, fd),
1296 ("fd_first_free() returned non-free descriptor"));
1297 KASSERT(fdp->fd_ofiles[fd] == NULL,
1298 ("free descriptor isn't"));
1299 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1306 * Check to see whether n user file descriptors
1307 * are available to the process p.
1310 fdavail(struct thread *td, int n)
1312 struct proc *p = td->td_proc;
1313 struct filedesc *fdp = td->td_proc->p_fd;
1317 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1320 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1322 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1324 last = min(fdp->fd_nfiles, lim);
1325 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1326 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1327 if (*fpp == NULL && --n <= 0)
1334 * Create a new open file structure and allocate
1335 * a file decriptor for the process that refers to it.
1336 * We add one reference to the file for the descriptor table
1337 * and one reference for resultfp. This is to prevent us being
1338 * preempted and the entry in the descriptor table closed after
1339 * we release the FILEDESC lock.
1342 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1344 struct proc *p = td->td_proc;
1345 struct file *fp, *fq;
1347 int maxuserfiles = maxfiles - (maxfiles / 20);
1348 static struct timeval lastfail;
1351 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1352 sx_xlock(&filelist_lock);
1354 if ((openfiles >= maxuserfiles &&
1355 priv_check_cred(td->td_ucred, PRIV_MAXFILES, SUSER_RUID) != 0) ||
1356 openfiles >= maxfiles) {
1357 if (ppsratecheck(&lastfail, &curfail, 1)) {
1358 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1359 td->td_ucred->cr_ruid);
1361 sx_xunlock(&filelist_lock);
1362 uma_zfree(file_zone, fp);
1368 * If the process has file descriptor zero open, add the new file
1369 * descriptor to the list of open files at that point, otherwise
1370 * put it at the front of the list of open files.
1372 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1376 fp->f_cred = crhold(td->td_ucred);
1377 fp->f_ops = &badfileops;
1380 FILEDESC_LOCK(p->p_fd);
1381 if ((fq = p->p_fd->fd_ofiles[0])) {
1382 LIST_INSERT_AFTER(fq, fp, f_list);
1384 LIST_INSERT_HEAD(&filehead, fp, f_list);
1386 sx_xunlock(&filelist_lock);
1387 if ((error = fdalloc(td, 0, &i))) {
1388 FILEDESC_UNLOCK(p->p_fd);
1394 p->p_fd->fd_ofiles[i] = fp;
1395 FILEDESC_UNLOCK(p->p_fd);
1404 * Build a new filedesc structure from another.
1405 * Copy the current, root, and jail root vnode references.
1408 fdinit(struct filedesc *fdp)
1410 struct filedesc0 *newfdp;
1412 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1413 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1416 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1417 if (newfdp->fd_fd.fd_cdir)
1418 VREF(newfdp->fd_fd.fd_cdir);
1419 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1420 if (newfdp->fd_fd.fd_rdir)
1421 VREF(newfdp->fd_fd.fd_rdir);
1422 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1423 if (newfdp->fd_fd.fd_jdir)
1424 VREF(newfdp->fd_fd.fd_jdir);
1425 FILEDESC_UNLOCK(fdp);
1428 /* Create the file descriptor table. */
1429 newfdp->fd_fd.fd_refcnt = 1;
1430 newfdp->fd_fd.fd_holdcnt = 1;
1431 newfdp->fd_fd.fd_cmask = CMASK;
1432 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1433 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1434 newfdp->fd_fd.fd_nfiles = NDFILE;
1435 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1436 newfdp->fd_fd.fd_lastfile = -1;
1437 return (&newfdp->fd_fd);
1440 static struct filedesc *
1441 fdhold(struct proc *p)
1443 struct filedesc *fdp;
1445 mtx_lock(&fdesc_mtx);
1449 mtx_unlock(&fdesc_mtx);
1454 fddrop(struct filedesc *fdp)
1458 mtx_lock(&fdesc_mtx);
1459 i = --fdp->fd_holdcnt;
1460 mtx_unlock(&fdesc_mtx);
1464 mtx_destroy(&fdp->fd_mtx);
1465 FREE(fdp, M_FILEDESC);
1469 * Share a filedesc structure.
1472 fdshare(struct filedesc *fdp)
1474 FILEDESC_LOCK_FAST(fdp);
1476 FILEDESC_UNLOCK_FAST(fdp);
1481 * Unshare a filedesc structure, if necessary by making a copy
1484 fdunshare(struct proc *p, struct thread *td)
1487 FILEDESC_LOCK_FAST(p->p_fd);
1488 if (p->p_fd->fd_refcnt > 1) {
1489 struct filedesc *tmp;
1491 FILEDESC_UNLOCK_FAST(p->p_fd);
1492 tmp = fdcopy(p->p_fd);
1496 FILEDESC_UNLOCK_FAST(p->p_fd);
1500 * Copy a filedesc structure.
1501 * A NULL pointer in returns a NULL reference, this is to ease callers,
1505 fdcopy(struct filedesc *fdp)
1507 struct filedesc *newfdp;
1510 /* Certain daemons might not have file descriptors. */
1514 newfdp = fdinit(fdp);
1515 FILEDESC_LOCK_FAST(fdp);
1516 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1517 FILEDESC_UNLOCK_FAST(fdp);
1518 FILEDESC_LOCK(newfdp);
1519 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1520 FILEDESC_UNLOCK(newfdp);
1521 FILEDESC_LOCK_FAST(fdp);
1523 /* copy everything except kqueue descriptors */
1524 newfdp->fd_freefile = -1;
1525 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1526 if (fdisused(fdp, i) &&
1527 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1528 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1529 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1530 fhold(newfdp->fd_ofiles[i]);
1531 newfdp->fd_lastfile = i;
1533 if (newfdp->fd_freefile == -1)
1534 newfdp->fd_freefile = i;
1537 FILEDESC_UNLOCK_FAST(fdp);
1538 FILEDESC_LOCK(newfdp);
1539 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1540 if (newfdp->fd_ofiles[i] != NULL)
1542 FILEDESC_UNLOCK(newfdp);
1543 FILEDESC_LOCK_FAST(fdp);
1544 if (newfdp->fd_freefile == -1)
1545 newfdp->fd_freefile = i;
1546 newfdp->fd_cmask = fdp->fd_cmask;
1547 FILEDESC_UNLOCK_FAST(fdp);
1552 * Release a filedesc structure.
1555 fdfree(struct thread *td)
1557 struct filedesc *fdp;
1560 struct filedesc_to_leader *fdtol;
1562 struct vnode *cdir, *jdir, *rdir, *vp;
1565 /* Certain daemons might not have file descriptors. */
1566 fdp = td->td_proc->p_fd;
1570 /* Check for special need to clear POSIX style locks */
1571 fdtol = td->td_proc->p_fdtol;
1572 if (fdtol != NULL) {
1574 KASSERT(fdtol->fdl_refcount > 0,
1575 ("filedesc_to_refcount botch: fdl_refcount=%d",
1576 fdtol->fdl_refcount));
1577 if (fdtol->fdl_refcount == 1 &&
1578 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1579 for (i = 0, fpp = fdp->fd_ofiles;
1580 i <= fdp->fd_lastfile;
1583 (*fpp)->f_type != DTYPE_VNODE)
1587 FILEDESC_UNLOCK(fdp);
1588 lf.l_whence = SEEK_SET;
1591 lf.l_type = F_UNLCK;
1593 locked = VFS_LOCK_GIANT(vp->v_mount);
1594 (void) VOP_ADVLOCK(vp,
1595 (caddr_t)td->td_proc->
1600 VFS_UNLOCK_GIANT(locked);
1603 fpp = fdp->fd_ofiles + i;
1607 if (fdtol->fdl_refcount == 1) {
1608 if (fdp->fd_holdleaderscount > 0 &&
1609 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1611 * close() or do_dup() has cleared a reference
1612 * in a shared file descriptor table.
1614 fdp->fd_holdleaderswakeup = 1;
1615 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1616 PLOCK, "fdlhold", 0);
1619 if (fdtol->fdl_holdcount > 0) {
1621 * Ensure that fdtol->fdl_leader
1622 * remains valid in closef().
1624 fdtol->fdl_wakeup = 1;
1625 msleep(fdtol, &fdp->fd_mtx,
1626 PLOCK, "fdlhold", 0);
1630 fdtol->fdl_refcount--;
1631 if (fdtol->fdl_refcount == 0 &&
1632 fdtol->fdl_holdcount == 0) {
1633 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1634 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1637 td->td_proc->p_fdtol = NULL;
1638 FILEDESC_UNLOCK(fdp);
1640 FREE(fdtol, M_FILEDESC_TO_LEADER);
1642 FILEDESC_LOCK_FAST(fdp);
1643 i = --fdp->fd_refcnt;
1644 FILEDESC_UNLOCK_FAST(fdp);
1648 * We are the last reference to the structure, so we can
1649 * safely assume it will not change out from under us.
1651 fpp = fdp->fd_ofiles;
1652 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1654 (void) closef(*fpp, td);
1658 /* XXX This should happen earlier. */
1659 mtx_lock(&fdesc_mtx);
1660 td->td_proc->p_fd = NULL;
1661 mtx_unlock(&fdesc_mtx);
1663 if (fdp->fd_nfiles > NDFILE)
1664 FREE(fdp->fd_ofiles, M_FILEDESC);
1665 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1666 FREE(fdp->fd_map, M_FILEDESC);
1670 cdir = fdp->fd_cdir;
1671 fdp->fd_cdir = NULL;
1672 rdir = fdp->fd_rdir;
1673 fdp->fd_rdir = NULL;
1674 jdir = fdp->fd_jdir;
1675 fdp->fd_jdir = NULL;
1676 FILEDESC_UNLOCK(fdp);
1679 locked = VFS_LOCK_GIANT(cdir->v_mount);
1681 VFS_UNLOCK_GIANT(locked);
1684 locked = VFS_LOCK_GIANT(rdir->v_mount);
1686 VFS_UNLOCK_GIANT(locked);
1689 locked = VFS_LOCK_GIANT(jdir->v_mount);
1691 VFS_UNLOCK_GIANT(locked);
1698 * For setugid programs, we don't want to people to use that setugidness
1699 * to generate error messages which write to a file which otherwise would
1700 * otherwise be off-limits to the process. We check for filesystems where
1701 * the vnode can change out from under us after execve (like [lin]procfs).
1703 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1704 * sufficient. We also don't check for setugidness since we know we are.
1707 is_unsafe(struct file *fp)
1709 if (fp->f_type == DTYPE_VNODE) {
1710 struct vnode *vp = fp->f_vnode;
1712 if ((vp->v_vflag & VV_PROCDEP) != 0)
1719 * Make this setguid thing safe, if at all possible.
1722 setugidsafety(struct thread *td)
1724 struct filedesc *fdp;
1727 /* Certain daemons might not have file descriptors. */
1728 fdp = td->td_proc->p_fd;
1733 * Note: fdp->fd_ofiles may be reallocated out from under us while
1734 * we are blocked in a close. Be careful!
1737 for (i = 0; i <= fdp->fd_lastfile; i++) {
1740 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1743 knote_fdclose(td, i);
1745 * NULL-out descriptor prior to close to avoid
1746 * a race while close blocks.
1748 fp = fdp->fd_ofiles[i];
1749 fdp->fd_ofiles[i] = NULL;
1750 fdp->fd_ofileflags[i] = 0;
1752 FILEDESC_UNLOCK(fdp);
1753 (void) closef(fp, td);
1757 FILEDESC_UNLOCK(fdp);
1761 * If a specific file object occupies a specific file descriptor,
1762 * close the file descriptor entry and drop a reference on the file
1763 * object. This is a convenience function to handle a subsequent
1764 * error in a function that calls falloc() that handles the race that
1765 * another thread might have closed the file descriptor out from under
1766 * the thread creating the file object.
1769 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1773 if (fdp->fd_ofiles[idx] == fp) {
1774 fdp->fd_ofiles[idx] = NULL;
1776 FILEDESC_UNLOCK(fdp);
1779 FILEDESC_UNLOCK(fdp);
1784 * Close any files on exec?
1787 fdcloseexec(struct thread *td)
1789 struct filedesc *fdp;
1792 /* Certain daemons might not have file descriptors. */
1793 fdp = td->td_proc->p_fd;
1800 * We cannot cache fd_ofiles or fd_ofileflags since operations
1801 * may block and rip them out from under us.
1803 for (i = 0; i <= fdp->fd_lastfile; i++) {
1804 if (fdp->fd_ofiles[i] != NULL &&
1805 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1806 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1809 knote_fdclose(td, i);
1811 * NULL-out descriptor prior to close to avoid
1812 * a race while close blocks.
1814 fp = fdp->fd_ofiles[i];
1815 fdp->fd_ofiles[i] = NULL;
1816 fdp->fd_ofileflags[i] = 0;
1818 if (fp->f_type == DTYPE_MQUEUE)
1819 mq_fdclose(td, i, fp);
1820 FILEDESC_UNLOCK(fdp);
1821 (void) closef(fp, td);
1825 FILEDESC_UNLOCK(fdp);
1829 * It is unsafe for set[ug]id processes to be started with file
1830 * descriptors 0..2 closed, as these descriptors are given implicit
1831 * significance in the Standard C library. fdcheckstd() will create a
1832 * descriptor referencing /dev/null for each of stdin, stdout, and
1833 * stderr that is not already open.
1836 fdcheckstd(struct thread *td)
1838 struct nameidata nd;
1839 struct filedesc *fdp;
1842 int fd, i, error, flags, devnull;
1844 fdp = td->td_proc->p_fd;
1847 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1850 for (i = 0; i < 3; i++) {
1851 if (fdp->fd_ofiles[i] != NULL)
1855 error = falloc(td, &fp, &fd);
1858 /* Note extra ref on `fp' held for us by falloc(). */
1859 KASSERT(fd == i, ("oof, we didn't get our fd"));
1860 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1862 flags = FREAD | FWRITE;
1863 error = vn_open(&nd, &flags, 0, fd);
1866 * Someone may have closed the entry in the
1867 * file descriptor table, so check it hasn't
1868 * changed before dropping the reference count.
1871 KASSERT(fdp->fd_ofiles[fd] == fp,
1872 ("table not shared, how did it change?"));
1873 fdp->fd_ofiles[fd] = NULL;
1875 FILEDESC_UNLOCK(fdp);
1880 vfslocked = NDHASGIANT(&nd);
1881 NDFREE(&nd, NDF_ONLY_PNBUF);
1883 fp->f_vnode = nd.ni_vp;
1884 if (fp->f_data == NULL)
1885 fp->f_data = nd.ni_vp;
1886 if (fp->f_ops == &badfileops)
1888 fp->f_type = DTYPE_VNODE;
1889 VOP_UNLOCK(nd.ni_vp, 0, td);
1890 VFS_UNLOCK_GIANT(vfslocked);
1894 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1903 * Internal form of close.
1904 * Decrement reference count on file structure.
1905 * Note: td may be NULL when closing a file that was being passed in a
1908 * XXXRW: Giant is not required for the caller, but often will be held; this
1909 * makes it moderately likely the Giant will be recursed in the VFS case.
1912 closef(struct file *fp, struct thread *td)
1916 struct filedesc_to_leader *fdtol;
1917 struct filedesc *fdp;
1920 * POSIX record locking dictates that any close releases ALL
1921 * locks owned by this process. This is handled by setting
1922 * a flag in the unlock to free ONLY locks obeying POSIX
1923 * semantics, and not to free BSD-style file locks.
1924 * If the descriptor was in a message, POSIX-style locks
1925 * aren't passed with the descriptor, and the thread pointer
1926 * will be NULL. Callers should be careful only to pass a
1927 * NULL thread pointer when there really is no owning
1928 * context that might have locks, or the locks will be
1931 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1935 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1936 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1937 lf.l_whence = SEEK_SET;
1940 lf.l_type = F_UNLCK;
1941 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1942 F_UNLCK, &lf, F_POSIX);
1944 fdtol = td->td_proc->p_fdtol;
1945 if (fdtol != NULL) {
1947 * Handle special case where file descriptor table
1948 * is shared between multiple process leaders.
1950 fdp = td->td_proc->p_fd;
1952 for (fdtol = fdtol->fdl_next;
1953 fdtol != td->td_proc->p_fdtol;
1954 fdtol = fdtol->fdl_next) {
1955 if ((fdtol->fdl_leader->p_flag &
1958 fdtol->fdl_holdcount++;
1959 FILEDESC_UNLOCK(fdp);
1960 lf.l_whence = SEEK_SET;
1963 lf.l_type = F_UNLCK;
1965 (void) VOP_ADVLOCK(vp,
1966 (caddr_t)fdtol->fdl_leader,
1967 F_UNLCK, &lf, F_POSIX);
1969 fdtol->fdl_holdcount--;
1970 if (fdtol->fdl_holdcount == 0 &&
1971 fdtol->fdl_wakeup != 0) {
1972 fdtol->fdl_wakeup = 0;
1976 FILEDESC_UNLOCK(fdp);
1978 VFS_UNLOCK_GIANT(vfslocked);
1980 return (fdrop(fp, td));
1984 * Extract the file pointer associated with the specified descriptor for
1985 * the current user process.
1987 * If the descriptor doesn't exist, EBADF is returned.
1989 * If the descriptor exists but doesn't match 'flags' then
1990 * return EBADF for read attempts and EINVAL for write attempts.
1992 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1993 * It should be dropped with fdrop().
1994 * If it is not set, then the refcount will not be bumped however the
1995 * thread's filedesc struct will be returned locked (for fgetsock).
1997 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1998 * Otherwise *fpp is set and zero is returned.
2001 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
2003 struct filedesc *fdp;
2007 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
2010 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
2011 FILEDESC_UNLOCK(fdp);
2016 * FREAD and FWRITE failure return EBADF as per POSIX.
2018 * Only one flag, or 0, may be specified.
2020 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
2021 FILEDESC_UNLOCK(fdp);
2024 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2025 FILEDESC_UNLOCK(fdp);
2030 FILEDESC_UNLOCK(fdp);
2037 fget(struct thread *td, int fd, struct file **fpp)
2040 return(_fget(td, fd, fpp, 0, 1));
2044 fget_read(struct thread *td, int fd, struct file **fpp)
2047 return(_fget(td, fd, fpp, FREAD, 1));
2051 fget_write(struct thread *td, int fd, struct file **fpp)
2054 return(_fget(td, fd, fpp, FWRITE, 1));
2058 * Like fget() but loads the underlying vnode, or returns an error if
2059 * the descriptor does not represent a vnode. Note that pipes use vnodes
2060 * but never have VM objects. The returned vnode will be vref()d.
2062 * XXX: what about the unused flags ?
2065 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2071 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2073 if (fp->f_vnode == NULL) {
2079 FILEDESC_UNLOCK(td->td_proc->p_fd);
2084 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2087 return (_fgetvp(td, fd, vpp, 0));
2091 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2094 return (_fgetvp(td, fd, vpp, FREAD));
2099 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2102 return (_fgetvp(td, fd, vpp, FWRITE));
2107 * Like fget() but loads the underlying socket, or returns an error if
2108 * the descriptor does not represent a socket.
2110 * We bump the ref count on the returned socket. XXX Also obtain the SX
2111 * lock in the future.
2113 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2114 * on their file descriptor reference to prevent the socket from being
2118 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2128 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2130 if (fp->f_type != DTYPE_SOCKET) {
2135 *fflagp = fp->f_flag;
2140 FILEDESC_UNLOCK(td->td_proc->p_fd);
2145 * Drop the reference count on the socket and XXX release the SX lock in the
2146 * future. The last reference closes the socket.
2148 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2151 fputsock(struct socket *so)
2161 fdrop(struct file *fp, struct thread *td)
2165 return (fdrop_locked(fp, td));
2169 * Drop reference on struct file passed in, may call closef if the
2170 * reference hits zero.
2171 * Expects struct file locked, and will unlock it.
2174 fdrop_locked(struct file *fp, struct thread *td)
2178 FILE_LOCK_ASSERT(fp, MA_OWNED);
2180 if (--fp->f_count > 0) {
2186 * We might have just dropped the last reference to a file
2187 * object that is for a UNIX domain socket whose message
2188 * buffers are being examined in unp_gc(). If that is the
2189 * case, FWAIT will be set in f_gcflag and we need to wait for
2190 * unp_gc() to finish its scan.
2192 while (fp->f_gcflag & FWAIT)
2193 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2195 /* We have the last ref so we can proceed without the file lock. */
2197 if (fp->f_count < 0)
2198 panic("fdrop: count < 0");
2199 if (fp->f_ops != &badfileops)
2200 error = fo_close(fp, td);
2204 sx_xlock(&filelist_lock);
2205 LIST_REMOVE(fp, f_list);
2207 sx_xunlock(&filelist_lock);
2209 uma_zfree(file_zone, fp);
2215 * Apply an advisory lock on a file descriptor.
2217 * Just attempt to get a record lock of the requested type on
2218 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2220 #ifndef _SYS_SYSPROTO_H_
2231 flock(struct thread *td, struct flock_args *uap)
2238 if ((error = fget(td, uap->fd, &fp)) != 0)
2240 if (fp->f_type != DTYPE_VNODE) {
2242 return (EOPNOTSUPP);
2247 lf.l_whence = SEEK_SET;
2250 if (uap->how & LOCK_UN) {
2251 lf.l_type = F_UNLCK;
2253 fp->f_flag &= ~FHASLOCK;
2255 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2258 if (uap->how & LOCK_EX)
2259 lf.l_type = F_WRLCK;
2260 else if (uap->how & LOCK_SH)
2261 lf.l_type = F_RDLCK;
2267 fp->f_flag |= FHASLOCK;
2269 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2270 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2277 * Duplicate the specified descriptor to a free descriptor.
2280 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2286 * If the to-be-dup'd fd number is greater than the allowed number
2287 * of file descriptors, or the fd to be dup'd has already been
2288 * closed, then reject.
2291 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2292 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2293 FILEDESC_UNLOCK(fdp);
2298 * There are two cases of interest here.
2300 * For ENODEV simply dup (dfd) to file descriptor
2301 * (indx) and return.
2303 * For ENXIO steal away the file structure from (dfd) and
2304 * store it in (indx). (dfd) is effectively closed by
2307 * Any other error code is just returned.
2312 * Check that the mode the file is being opened for is a
2313 * subset of the mode of the existing descriptor.
2316 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2318 FILEDESC_UNLOCK(fdp);
2321 fp = fdp->fd_ofiles[indx];
2322 fdp->fd_ofiles[indx] = wfp;
2323 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2328 FILEDESC_UNLOCK(fdp);
2331 * We now own the reference to fp that the ofiles[]
2332 * array used to own. Release it.
2335 fdrop_locked(fp, td);
2341 * Steal away the file pointer from dfd and stuff it into indx.
2343 fp = fdp->fd_ofiles[indx];
2344 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2345 fdp->fd_ofiles[dfd] = NULL;
2346 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2347 fdp->fd_ofileflags[dfd] = 0;
2355 * We now own the reference to fp that the ofiles[] array
2356 * used to own. Release it.
2359 fdrop_locked(fp, td);
2361 FILEDESC_UNLOCK(fdp);
2366 FILEDESC_UNLOCK(fdp);
2373 * Scan all active processes to see if any of them have a current
2374 * or root directory of `olddp'. If so, replace them with the new
2378 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2380 struct filedesc *fdp;
2384 if (vrefcnt(olddp) == 1)
2386 sx_slock(&allproc_lock);
2387 FOREACH_PROC_IN_SYSTEM(p) {
2392 FILEDESC_LOCK_FAST(fdp);
2393 if (fdp->fd_cdir == olddp) {
2395 fdp->fd_cdir = newdp;
2398 if (fdp->fd_rdir == olddp) {
2400 fdp->fd_rdir = newdp;
2403 FILEDESC_UNLOCK_FAST(fdp);
2408 sx_sunlock(&allproc_lock);
2409 if (rootvnode == olddp) {
2416 struct filedesc_to_leader *
2417 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2419 struct filedesc_to_leader *fdtol;
2421 MALLOC(fdtol, struct filedesc_to_leader *,
2422 sizeof(struct filedesc_to_leader),
2423 M_FILEDESC_TO_LEADER,
2425 fdtol->fdl_refcount = 1;
2426 fdtol->fdl_holdcount = 0;
2427 fdtol->fdl_wakeup = 0;
2428 fdtol->fdl_leader = leader;
2431 fdtol->fdl_next = old->fdl_next;
2432 fdtol->fdl_prev = old;
2433 old->fdl_next = fdtol;
2434 fdtol->fdl_next->fdl_prev = fdtol;
2435 FILEDESC_UNLOCK(fdp);
2437 fdtol->fdl_next = fdtol;
2438 fdtol->fdl_prev = fdtol;
2444 * Get file structures.
2447 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2450 struct filedesc *fdp;
2456 * Note: because the number of file descriptors is calculated
2457 * in different ways for sizing vs returning the data,
2458 * there is information leakage from the first loop. However,
2459 * it is of a similar order of magnitude to the leakage from
2460 * global system statistics such as kern.openfiles.
2462 error = sysctl_wire_old_buffer(req, 0);
2465 if (req->oldptr == NULL) {
2466 n = 16; /* A slight overestimate. */
2467 sx_slock(&filelist_lock);
2468 LIST_FOREACH(fp, &filehead, f_list) {
2470 * We should grab the lock, but this is an
2471 * estimate, so does it really matter?
2473 /* mtx_lock(fp->f_mtxp); */
2475 /* mtx_unlock(f->f_mtxp); */
2477 sx_sunlock(&filelist_lock);
2478 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2481 bzero(&xf, sizeof(xf));
2482 xf.xf_size = sizeof(xf);
2483 sx_slock(&allproc_lock);
2484 FOREACH_PROC_IN_SYSTEM(p) {
2485 if (p->p_state == PRS_NEW)
2488 if (p_cansee(req->td, p) != 0) {
2492 xf.xf_pid = p->p_pid;
2493 xf.xf_uid = p->p_ucred->cr_uid;
2498 FILEDESC_LOCK_FAST(fdp);
2499 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2500 if ((fp = fdp->fd_ofiles[n]) == NULL)
2504 xf.xf_data = fp->f_data;
2505 xf.xf_vnode = fp->f_vnode;
2506 xf.xf_type = fp->f_type;
2507 xf.xf_count = fp->f_count;
2508 xf.xf_msgcount = fp->f_msgcount;
2509 xf.xf_offset = fp->f_offset;
2510 xf.xf_flag = fp->f_flag;
2511 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2515 FILEDESC_UNLOCK_FAST(fdp);
2520 sx_sunlock(&allproc_lock);
2524 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2525 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2529 * For the purposes of debugging, generate a human-readable string for the
2533 file_type_to_name(short type)
2555 * For the purposes of debugging, identify a process (if any, perhaps one of
2556 * many) that references the passed file in its file descriptor array. Return
2559 static struct proc *
2560 file_to_first_proc(struct file *fp)
2562 struct filedesc *fdp;
2566 FOREACH_PROC_IN_SYSTEM(p) {
2567 if (p->p_state == PRS_NEW)
2572 for (n = 0; n < fdp->fd_nfiles; n++) {
2573 if (fp == fdp->fd_ofiles[n])
2580 DB_SHOW_COMMAND(files, db_show_files)
2585 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
2586 "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
2588 LIST_FOREACH(fp, &filehead, f_list) {
2589 p = file_to_first_proc(fp);
2590 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2591 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2592 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2593 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2598 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2599 &maxfilesperproc, 0, "Maximum files allowed open per process");
2601 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2602 &maxfiles, 0, "Maximum number of files");
2604 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2605 &openfiles, 0, "System-wide number of open files");
2609 filelistinit(void *dummy)
2612 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2613 NULL, NULL, UMA_ALIGN_PTR, 0);
2614 sx_init(&filelist_lock, "filelist lock");
2615 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2616 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2618 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2620 /*-------------------------------------------------------------------*/
2623 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2630 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2637 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2644 badfo_kqfilter(struct file *fp, struct knote *kn)
2651 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2658 badfo_close(struct file *fp, struct thread *td)
2664 struct fileops badfileops = {
2665 .fo_read = badfo_readwrite,
2666 .fo_write = badfo_readwrite,
2667 .fo_ioctl = badfo_ioctl,
2668 .fo_poll = badfo_poll,
2669 .fo_kqfilter = badfo_kqfilter,
2670 .fo_stat = badfo_stat,
2671 .fo_close = badfo_close,
2675 /*-------------------------------------------------------------------*/
2678 * File Descriptor pseudo-device driver (/dev/fd/).
2680 * Opening minor device N dup()s the file (if any) connected to file
2681 * descriptor N belonging to the calling process. Note that this driver
2682 * consists of only the ``open()'' routine, because all subsequent
2683 * references to this file will be direct to the other driver.
2685 * XXX: we could give this one a cloning event handler if necessary.
2690 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2694 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2695 * the file descriptor being sought for duplication. The error
2696 * return ensures that the vnode for this device will be released
2697 * by vn_open. Open will detect this special error and take the
2698 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2699 * will simply report the error.
2701 td->td_dupfd = dev2unit(dev);
2705 static struct cdevsw fildesc_cdevsw = {
2706 .d_version = D_VERSION,
2707 .d_flags = D_NEEDGIANT,
2713 fildesc_drvinit(void *unused)
2717 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2718 make_dev_alias(dev, "stdin");
2719 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2720 make_dev_alias(dev, "stdout");
2721 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2722 make_dev_alias(dev, "stderr");
2725 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)