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)
215 FILEDESC_XLOCK_ASSERT(fdp);
216 KASSERT(!fdisused(fdp, fd),
217 ("fd already used"));
219 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
220 if (fd > fdp->fd_lastfile)
221 fdp->fd_lastfile = fd;
222 if (fd == fdp->fd_freefile)
223 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
227 * Mark a file descriptor as unused.
230 fdunused(struct filedesc *fdp, int fd)
233 FILEDESC_XLOCK_ASSERT(fdp);
234 KASSERT(fdisused(fdp, fd),
235 ("fd is already unused"));
236 KASSERT(fdp->fd_ofiles[fd] == NULL,
237 ("fd is still in use"));
239 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
240 if (fd < fdp->fd_freefile)
241 fdp->fd_freefile = fd;
242 if (fd == fdp->fd_lastfile)
243 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
247 * System calls on descriptors.
249 #ifndef _SYS_SYSPROTO_H_
250 struct getdtablesize_args {
256 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
258 struct proc *p = td->td_proc;
262 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
268 * Duplicate a file descriptor to a particular value.
270 * Note: keep in mind that a potential race condition exists when closing
271 * descriptors from a shared descriptor table (via rfork).
273 #ifndef _SYS_SYSPROTO_H_
281 dup2(struct thread *td, struct dup2_args *uap)
284 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
289 * Duplicate a file descriptor.
291 #ifndef _SYS_SYSPROTO_H_
298 dup(struct thread *td, struct dup_args *uap)
301 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
305 * The file control system call.
307 #ifndef _SYS_SYSPROTO_H_
316 fcntl(struct thread *td, struct fcntl_args *uap)
327 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
336 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
339 if (uap->cmd == F_GETLK)
340 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
345 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
347 struct filedesc *fdp;
358 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
359 * avoid grabbing Giant for calls we know don't need it.
380 * XXXRW: It could be an exclusive lock is not [always] needed here.
383 if ((unsigned)fd >= fdp->fd_nfiles ||
384 (fp = fdp->fd_ofiles[fd]) == NULL) {
385 FILEDESC_XUNLOCK(fdp);
389 pop = &fdp->fd_ofileflags[fd];
393 /* mtx_assert(&Giant, MA_NOTOWNED); */
394 FILEDESC_XUNLOCK(fdp);
397 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
398 newmin >= maxfilesperproc) {
404 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
408 /* mtx_assert(&Giant, MA_NOTOWNED); */
409 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
410 FILEDESC_XUNLOCK(fdp);
414 /* mtx_assert(&Giant, MA_NOTOWNED); */
415 *pop = (*pop &~ UF_EXCLOSE) |
416 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
417 FILEDESC_XUNLOCK(fdp);
421 /* mtx_assert(&Giant, MA_NOTOWNED); */
423 td->td_retval[0] = OFLAGS(fp->f_flag);
425 FILEDESC_XUNLOCK(fdp);
429 mtx_assert(&Giant, MA_OWNED);
432 fp->f_flag &= ~FCNTLFLAGS;
433 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
435 FILEDESC_XUNLOCK(fdp);
436 tmp = fp->f_flag & FNONBLOCK;
437 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
442 tmp = fp->f_flag & FASYNC;
443 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
449 fp->f_flag &= ~FNONBLOCK;
452 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
457 mtx_assert(&Giant, MA_OWNED);
459 FILEDESC_XUNLOCK(fdp);
460 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
462 td->td_retval[0] = tmp;
467 mtx_assert(&Giant, MA_OWNED);
469 FILEDESC_XUNLOCK(fdp);
471 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
476 mtx_assert(&Giant, MA_OWNED);
478 /* FALLTHROUGH F_SETLK */
481 mtx_assert(&Giant, MA_OWNED);
482 if (fp->f_type != DTYPE_VNODE) {
483 FILEDESC_XUNLOCK(fdp);
488 flp = (struct flock *)arg;
489 if (flp->l_whence == SEEK_CUR) {
490 if (fp->f_offset < 0 ||
492 fp->f_offset > OFF_MAX - flp->l_start)) {
493 FILEDESC_XUNLOCK(fdp);
497 flp->l_start += fp->f_offset;
501 * VOP_ADVLOCK() may block.
504 FILEDESC_XUNLOCK(fdp);
507 switch (flp->l_type) {
509 if ((fp->f_flag & FREAD) == 0) {
513 PROC_LOCK(p->p_leader);
514 p->p_leader->p_flag |= P_ADVLOCK;
515 PROC_UNLOCK(p->p_leader);
516 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
520 if ((fp->f_flag & FWRITE) == 0) {
524 PROC_LOCK(p->p_leader);
525 p->p_leader->p_flag |= P_ADVLOCK;
526 PROC_UNLOCK(p->p_leader);
527 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
531 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
538 /* Check for race with close */
540 if ((unsigned) fd >= fdp->fd_nfiles ||
541 fp != fdp->fd_ofiles[fd]) {
542 FILEDESC_XUNLOCK(fdp);
543 flp->l_whence = SEEK_SET;
546 flp->l_type = F_UNLCK;
547 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
548 F_UNLCK, flp, F_POSIX);
550 FILEDESC_XUNLOCK(fdp);
555 mtx_assert(&Giant, MA_OWNED);
556 if (fp->f_type != DTYPE_VNODE) {
557 FILEDESC_XUNLOCK(fdp);
561 flp = (struct flock *)arg;
562 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
563 flp->l_type != F_UNLCK) {
564 FILEDESC_XUNLOCK(fdp);
568 if (flp->l_whence == SEEK_CUR) {
569 if ((flp->l_start > 0 &&
570 fp->f_offset > OFF_MAX - flp->l_start) ||
572 fp->f_offset < OFF_MIN - flp->l_start)) {
573 FILEDESC_XUNLOCK(fdp);
577 flp->l_start += fp->f_offset;
580 * VOP_ADVLOCK() may block.
583 FILEDESC_XUNLOCK(fdp);
585 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
590 FILEDESC_XUNLOCK(fdp);
601 * Common code for dup, dup2, and fcntl(F_DUPFD).
604 do_dup(struct thread *td, enum dup_type type, int old, int new,
607 struct filedesc *fdp;
611 int error, holdleaders, maxfd;
613 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
614 ("invalid dup type %d", type));
620 * Verify we have a valid descriptor to dup from and possibly to
623 if (old < 0 || new < 0)
626 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
632 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
633 FILEDESC_XUNLOCK(fdp);
636 if (type == DUP_FIXED && old == new) {
638 FILEDESC_XUNLOCK(fdp);
641 fp = fdp->fd_ofiles[old];
645 * If the caller specified a file descriptor, make sure the file
646 * table is large enough to hold it, and grab it. Otherwise, just
647 * allocate a new descriptor the usual way. Since the filedesc
648 * lock may be temporarily dropped in the process, we have to look
651 if (type == DUP_FIXED) {
652 if (new >= fdp->fd_nfiles)
653 fdgrowtable(fdp, new + 1);
654 if (fdp->fd_ofiles[new] == NULL)
657 if ((error = fdalloc(td, new, &new)) != 0) {
658 FILEDESC_XUNLOCK(fdp);
665 * If the old file changed out from under us then treat it as a
666 * bad file descriptor. Userland should do its own locking to
669 if (fdp->fd_ofiles[old] != fp ||
670 (fdp->fd_ofileflags[old] & UF_OPENING) != 0 ||
671 (fdp->fd_ofileflags[new] & UF_OPENING) != 0) {
672 /* we've allocated a descriptor which we won't use */
673 if (fdp->fd_ofiles[new] == NULL)
675 FILEDESC_XUNLOCK(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_XUNLOCK(fdp);
723 (void) closef(delfp, td);
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_XUNLOCK(fdp);
735 FILEDESC_XUNLOCK(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_
971 struct close_args *uap;
974 return (kern_close(td, uap->fd));
982 struct filedesc *fdp;
989 fdp = td->td_proc->p_fd;
991 AUDIT_SYSCLOSE(td, fd);
994 if ((unsigned)fd >= fdp->fd_nfiles ||
995 (fp = fdp->fd_ofiles[fd]) == NULL ||
996 (fdp->fd_ofileflags[fd] & UF_OPENING) != 0) {
997 FILEDESC_XUNLOCK(fdp);
1000 fdp->fd_ofiles[fd] = NULL;
1001 fdp->fd_ofileflags[fd] = 0;
1003 if (td->td_proc->p_fdtol != NULL) {
1005 * Ask fdfree() to sleep to ensure that all relevant
1006 * process leaders can be traversed in closef().
1008 fdp->fd_holdleaderscount++;
1013 * We now hold the fp reference that used to be owned by the
1014 * descriptor array. We have to unlock the FILEDESC *AFTER*
1015 * knote_fdclose to prevent a race of the fd getting opened, a knote
1016 * added, and deleteing a knote for the new fd.
1018 knote_fdclose(td, fd);
1019 if (fp->f_type == DTYPE_MQUEUE)
1020 mq_fdclose(td, fd, fp);
1021 FILEDESC_XUNLOCK(fdp);
1023 error = closef(fp, td);
1025 FILEDESC_XLOCK(fdp);
1026 fdp->fd_holdleaderscount--;
1027 if (fdp->fd_holdleaderscount == 0 &&
1028 fdp->fd_holdleaderswakeup != 0) {
1029 fdp->fd_holdleaderswakeup = 0;
1030 wakeup(&fdp->fd_holdleaderscount);
1032 FILEDESC_XUNLOCK(fdp);
1037 #if defined(COMPAT_43)
1039 * Return status information about a file descriptor.
1041 #ifndef _SYS_SYSPROTO_H_
1042 struct ofstat_args {
1049 ofstat(struct thread *td, struct ofstat_args *uap)
1055 error = kern_fstat(td, uap->fd, &ub);
1058 error = copyout(&oub, uap->sb, sizeof(oub));
1062 #endif /* COMPAT_43 */
1065 * Return status information about a file descriptor.
1067 #ifndef _SYS_SYSPROTO_H_
1075 fstat(struct thread *td, struct fstat_args *uap)
1080 error = kern_fstat(td, uap->fd, &ub);
1082 error = copyout(&ub, uap->sb, sizeof(ub));
1087 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1094 if ((error = fget(td, fd, &fp)) != 0)
1097 AUDIT_ARG(file, td->td_proc, fp);
1099 error = fo_stat(fp, sbp, td->td_ucred, td);
1105 * Return status information about a file descriptor.
1107 #ifndef _SYS_SYSPROTO_H_
1108 struct nfstat_args {
1115 nfstat(struct thread *td, struct nfstat_args *uap)
1121 error = kern_fstat(td, uap->fd, &ub);
1123 cvtnstat(&ub, &nub);
1124 error = copyout(&nub, uap->sb, sizeof(nub));
1130 * Return pathconf information about a file descriptor.
1132 #ifndef _SYS_SYSPROTO_H_
1133 struct fpathconf_args {
1140 fpathconf(struct thread *td, struct fpathconf_args *uap)
1146 if ((error = fget(td, uap->fd, &fp)) != 0)
1149 /* If asynchronous I/O is available, it works for all descriptors. */
1150 if (uap->name == _PC_ASYNC_IO) {
1151 td->td_retval[0] = async_io_version;
1157 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1158 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1159 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1160 VOP_UNLOCK(vp, 0, td);
1161 VFS_UNLOCK_GIANT(vfslocked);
1162 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1163 if (uap->name != _PC_PIPE_BUF) {
1166 td->td_retval[0] = PIPE_BUF;
1178 * Grow the file table to accomodate (at least) nfd descriptors. This may
1179 * block and drop the filedesc lock, but it will reacquire it before
1183 fdgrowtable(struct filedesc *fdp, int nfd)
1185 struct file **ntable;
1187 int nnfiles, onfiles;
1190 FILEDESC_XLOCK_ASSERT(fdp);
1192 KASSERT(fdp->fd_nfiles > 0,
1193 ("zero-length file table"));
1195 /* compute the size of the new table */
1196 onfiles = fdp->fd_nfiles;
1197 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1198 if (nnfiles <= onfiles)
1199 /* the table is already large enough */
1202 /* allocate a new table and (if required) new bitmaps */
1203 FILEDESC_XUNLOCK(fdp);
1204 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1205 M_FILEDESC, M_ZERO | M_WAITOK);
1206 nfileflags = (char *)&ntable[nnfiles];
1207 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1208 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1209 M_FILEDESC, M_ZERO | M_WAITOK);
1212 FILEDESC_XLOCK(fdp);
1215 * We now have new tables ready to go. Since we dropped the
1216 * filedesc lock to call malloc(), watch out for a race.
1218 onfiles = fdp->fd_nfiles;
1219 if (onfiles >= nnfiles) {
1220 /* we lost the race, but that's OK */
1221 free(ntable, M_FILEDESC);
1223 free(nmap, M_FILEDESC);
1226 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1227 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1228 if (onfiles > NDFILE)
1229 free(fdp->fd_ofiles, M_FILEDESC);
1230 fdp->fd_ofiles = ntable;
1231 fdp->fd_ofileflags = nfileflags;
1232 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1233 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1234 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1235 free(fdp->fd_map, M_FILEDESC);
1238 fdp->fd_nfiles = nnfiles;
1242 * Allocate a file descriptor for the process.
1245 fdalloc(struct thread *td, int minfd, int *result)
1247 struct proc *p = td->td_proc;
1248 struct filedesc *fdp = p->p_fd;
1251 FILEDESC_XLOCK_ASSERT(fdp);
1253 if (fdp->fd_freefile > minfd)
1254 minfd = fdp->fd_freefile;
1257 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1261 * Search the bitmap for a free descriptor. If none is found, try
1262 * to grow the file table. Keep at it until we either get a file
1263 * descriptor or run into process or system limits; fdgrowtable()
1264 * may drop the filedesc lock, so we're in a race.
1267 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1270 if (fd < fdp->fd_nfiles)
1272 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1276 * Perform some sanity checks, then mark the file descriptor as
1277 * used and return it to the caller.
1279 KASSERT(!fdisused(fdp, fd),
1280 ("fd_first_free() returned non-free descriptor"));
1281 KASSERT(fdp->fd_ofiles[fd] == NULL,
1282 ("free descriptor isn't"));
1283 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1290 * Check to see whether n user file descriptors are available to the process
1294 fdavail(struct thread *td, int n)
1296 struct proc *p = td->td_proc;
1297 struct filedesc *fdp = td->td_proc->p_fd;
1301 FILEDESC_LOCK_ASSERT(fdp);
1304 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1306 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1308 last = min(fdp->fd_nfiles, lim);
1309 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1310 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1311 if (*fpp == NULL && --n <= 0)
1318 * Create a new open file structure and allocate a file decriptor for the
1319 * process that refers to it. We add one reference to the file for the
1320 * descriptor table and one reference for resultfp. This is to prevent us
1321 * being preempted and the entry in the descriptor table closed after we
1322 * release the FILEDESC lock.
1325 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1327 struct proc *p = td->td_proc;
1328 struct file *fp, *fq;
1330 int maxuserfiles = maxfiles - (maxfiles / 20);
1331 static struct timeval lastfail;
1334 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1335 sx_xlock(&filelist_lock);
1337 if ((openfiles >= maxuserfiles &&
1338 priv_check_cred(td->td_ucred, PRIV_MAXFILES, SUSER_RUID) != 0) ||
1339 openfiles >= maxfiles) {
1340 if (ppsratecheck(&lastfail, &curfail, 1)) {
1341 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1342 td->td_ucred->cr_ruid);
1344 sx_xunlock(&filelist_lock);
1345 uma_zfree(file_zone, fp);
1351 * If the process has file descriptor zero open, add the new file
1352 * descriptor to the list of open files at that point, otherwise
1353 * put it at the front of the list of open files.
1355 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1359 fp->f_cred = crhold(td->td_ucred);
1360 fp->f_ops = &badfileops;
1363 FILEDESC_XLOCK(p->p_fd);
1364 if ((fq = p->p_fd->fd_ofiles[0])) {
1365 LIST_INSERT_AFTER(fq, fp, f_list);
1367 LIST_INSERT_HEAD(&filehead, fp, f_list);
1369 sx_xunlock(&filelist_lock);
1370 if ((error = fdalloc(td, 0, &i))) {
1371 FILEDESC_XUNLOCK(p->p_fd);
1377 p->p_fd->fd_ofiles[i] = fp;
1378 FILEDESC_XUNLOCK(p->p_fd);
1387 * Build a new filedesc structure from another.
1388 * Copy the current, root, and jail root vnode references.
1391 fdinit(struct filedesc *fdp)
1393 struct filedesc0 *newfdp;
1395 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1396 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1398 FILEDESC_XLOCK(fdp);
1399 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1400 if (newfdp->fd_fd.fd_cdir)
1401 VREF(newfdp->fd_fd.fd_cdir);
1402 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1403 if (newfdp->fd_fd.fd_rdir)
1404 VREF(newfdp->fd_fd.fd_rdir);
1405 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1406 if (newfdp->fd_fd.fd_jdir)
1407 VREF(newfdp->fd_fd.fd_jdir);
1408 FILEDESC_XUNLOCK(fdp);
1411 /* Create the file descriptor table. */
1412 newfdp->fd_fd.fd_refcnt = 1;
1413 newfdp->fd_fd.fd_holdcnt = 1;
1414 newfdp->fd_fd.fd_cmask = CMASK;
1415 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1416 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1417 newfdp->fd_fd.fd_nfiles = NDFILE;
1418 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1419 newfdp->fd_fd.fd_lastfile = -1;
1420 return (&newfdp->fd_fd);
1423 static struct filedesc *
1424 fdhold(struct proc *p)
1426 struct filedesc *fdp;
1428 mtx_lock(&fdesc_mtx);
1432 mtx_unlock(&fdesc_mtx);
1437 fddrop(struct filedesc *fdp)
1441 mtx_lock(&fdesc_mtx);
1442 i = --fdp->fd_holdcnt;
1443 mtx_unlock(&fdesc_mtx);
1447 FILEDESC_LOCK_DESTROY(fdp);
1448 FREE(fdp, M_FILEDESC);
1452 * Share a filedesc structure.
1455 fdshare(struct filedesc *fdp)
1458 FILEDESC_XLOCK(fdp);
1460 FILEDESC_XUNLOCK(fdp);
1465 * Unshare a filedesc structure, if necessary by making a copy
1468 fdunshare(struct proc *p, struct thread *td)
1471 FILEDESC_XLOCK(p->p_fd);
1472 if (p->p_fd->fd_refcnt > 1) {
1473 struct filedesc *tmp;
1475 FILEDESC_XUNLOCK(p->p_fd);
1476 tmp = fdcopy(p->p_fd);
1480 FILEDESC_XUNLOCK(p->p_fd);
1484 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1485 * this is to ease callers, not catch errors.
1488 fdcopy(struct filedesc *fdp)
1490 struct filedesc *newfdp;
1493 /* Certain daemons might not have file descriptors. */
1497 newfdp = fdinit(fdp);
1498 FILEDESC_SLOCK(fdp);
1499 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1500 FILEDESC_SUNLOCK(fdp);
1501 FILEDESC_XLOCK(newfdp);
1502 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1503 FILEDESC_XUNLOCK(newfdp);
1504 FILEDESC_SLOCK(fdp);
1506 /* copy everything except kqueue descriptors */
1507 newfdp->fd_freefile = -1;
1508 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1509 if (fdisused(fdp, i) &&
1510 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE &&
1511 (fdp->fd_ofileflags[i] & UF_OPENING) == 0) {
1512 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1513 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1514 fhold(newfdp->fd_ofiles[i]);
1515 newfdp->fd_lastfile = i;
1517 if (newfdp->fd_freefile == -1)
1518 newfdp->fd_freefile = i;
1521 FILEDESC_SUNLOCK(fdp);
1522 FILEDESC_XLOCK(newfdp);
1523 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1524 if (newfdp->fd_ofiles[i] != NULL)
1526 FILEDESC_XUNLOCK(newfdp);
1527 FILEDESC_SLOCK(fdp);
1528 if (newfdp->fd_freefile == -1)
1529 newfdp->fd_freefile = i;
1530 newfdp->fd_cmask = fdp->fd_cmask;
1531 FILEDESC_SUNLOCK(fdp);
1536 * Release a filedesc structure.
1539 fdfree(struct thread *td)
1541 struct filedesc *fdp;
1544 struct filedesc_to_leader *fdtol;
1546 struct vnode *cdir, *jdir, *rdir, *vp;
1549 /* Certain daemons might not have file descriptors. */
1550 fdp = td->td_proc->p_fd;
1554 /* Check for special need to clear POSIX style locks */
1555 fdtol = td->td_proc->p_fdtol;
1556 if (fdtol != NULL) {
1557 FILEDESC_XLOCK(fdp);
1558 KASSERT(fdtol->fdl_refcount > 0,
1559 ("filedesc_to_refcount botch: fdl_refcount=%d",
1560 fdtol->fdl_refcount));
1561 if (fdtol->fdl_refcount == 1 &&
1562 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1563 for (i = 0, fpp = fdp->fd_ofiles;
1564 i <= fdp->fd_lastfile;
1567 (*fpp)->f_type != DTYPE_VNODE)
1571 FILEDESC_XUNLOCK(fdp);
1572 lf.l_whence = SEEK_SET;
1575 lf.l_type = F_UNLCK;
1577 locked = VFS_LOCK_GIANT(vp->v_mount);
1578 (void) VOP_ADVLOCK(vp,
1579 (caddr_t)td->td_proc->
1584 VFS_UNLOCK_GIANT(locked);
1585 FILEDESC_XLOCK(fdp);
1587 fpp = fdp->fd_ofiles + i;
1591 if (fdtol->fdl_refcount == 1) {
1592 if (fdp->fd_holdleaderscount > 0 &&
1593 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1595 * close() or do_dup() has cleared a reference
1596 * in a shared file descriptor table.
1598 fdp->fd_holdleaderswakeup = 1;
1599 sx_sleep(&fdp->fd_holdleaderscount,
1600 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1603 if (fdtol->fdl_holdcount > 0) {
1605 * Ensure that fdtol->fdl_leader remains
1606 * valid in closef().
1608 fdtol->fdl_wakeup = 1;
1609 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1614 fdtol->fdl_refcount--;
1615 if (fdtol->fdl_refcount == 0 &&
1616 fdtol->fdl_holdcount == 0) {
1617 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1618 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1621 td->td_proc->p_fdtol = NULL;
1622 FILEDESC_XUNLOCK(fdp);
1624 FREE(fdtol, M_FILEDESC_TO_LEADER);
1626 FILEDESC_XLOCK(fdp);
1627 i = --fdp->fd_refcnt;
1628 FILEDESC_XUNLOCK(fdp);
1632 * We are the last reference to the structure, so we can
1633 * safely assume it will not change out from under us.
1635 fpp = fdp->fd_ofiles;
1636 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1638 (void) closef(*fpp, td);
1640 FILEDESC_XLOCK(fdp);
1642 /* XXX This should happen earlier. */
1643 mtx_lock(&fdesc_mtx);
1644 td->td_proc->p_fd = NULL;
1645 mtx_unlock(&fdesc_mtx);
1647 if (fdp->fd_nfiles > NDFILE)
1648 FREE(fdp->fd_ofiles, M_FILEDESC);
1649 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1650 FREE(fdp->fd_map, M_FILEDESC);
1654 cdir = fdp->fd_cdir;
1655 fdp->fd_cdir = NULL;
1656 rdir = fdp->fd_rdir;
1657 fdp->fd_rdir = NULL;
1658 jdir = fdp->fd_jdir;
1659 fdp->fd_jdir = NULL;
1660 FILEDESC_XUNLOCK(fdp);
1663 locked = VFS_LOCK_GIANT(cdir->v_mount);
1665 VFS_UNLOCK_GIANT(locked);
1668 locked = VFS_LOCK_GIANT(rdir->v_mount);
1670 VFS_UNLOCK_GIANT(locked);
1673 locked = VFS_LOCK_GIANT(jdir->v_mount);
1675 VFS_UNLOCK_GIANT(locked);
1682 * For setugid programs, we don't want to people to use that setugidness
1683 * to generate error messages which write to a file which otherwise would
1684 * otherwise be off-limits to the process. We check for filesystems where
1685 * the vnode can change out from under us after execve (like [lin]procfs).
1687 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1688 * sufficient. We also don't check for setugidness since we know we are.
1691 is_unsafe(struct file *fp)
1693 if (fp->f_type == DTYPE_VNODE) {
1694 struct vnode *vp = fp->f_vnode;
1696 if ((vp->v_vflag & VV_PROCDEP) != 0)
1703 * Make this setguid thing safe, if at all possible.
1706 setugidsafety(struct thread *td)
1708 struct filedesc *fdp;
1711 /* Certain daemons might not have file descriptors. */
1712 fdp = td->td_proc->p_fd;
1717 * Note: fdp->fd_ofiles may be reallocated out from under us while
1718 * we are blocked in a close. Be careful!
1720 FILEDESC_XLOCK(fdp);
1721 for (i = 0; i <= fdp->fd_lastfile; i++) {
1724 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1727 knote_fdclose(td, i);
1729 * NULL-out descriptor prior to close to avoid
1730 * a race while close blocks.
1732 fp = fdp->fd_ofiles[i];
1733 fdp->fd_ofiles[i] = NULL;
1734 fdp->fd_ofileflags[i] = 0;
1736 FILEDESC_XUNLOCK(fdp);
1737 (void) closef(fp, td);
1738 FILEDESC_XLOCK(fdp);
1741 FILEDESC_XUNLOCK(fdp);
1745 * If a specific file object occupies a specific file descriptor, close the
1746 * file descriptor entry and drop a reference on the file object. This is a
1747 * convenience function to handle a subsequent error in a function that calls
1748 * falloc() that handles the race that another thread might have closed the
1749 * file descriptor out from under the thread creating the file object.
1752 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1755 FILEDESC_XLOCK(fdp);
1756 if (fdp->fd_ofiles[idx] == fp) {
1757 fdp->fd_ofiles[idx] = NULL;
1759 FILEDESC_XUNLOCK(fdp);
1762 FILEDESC_XUNLOCK(fdp);
1766 * Close any files on exec?
1769 fdcloseexec(struct thread *td)
1771 struct filedesc *fdp;
1774 /* Certain daemons might not have file descriptors. */
1775 fdp = td->td_proc->p_fd;
1779 FILEDESC_XLOCK(fdp);
1782 * We cannot cache fd_ofiles or fd_ofileflags since operations
1783 * may block and rip them out from under us.
1785 for (i = 0; i <= fdp->fd_lastfile; i++) {
1786 if (fdp->fd_ofiles[i] != NULL &&
1787 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1788 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1791 knote_fdclose(td, i);
1793 * NULL-out descriptor prior to close to avoid
1794 * a race while close blocks.
1796 fp = fdp->fd_ofiles[i];
1797 fdp->fd_ofiles[i] = NULL;
1798 fdp->fd_ofileflags[i] = 0;
1800 if (fp->f_type == DTYPE_MQUEUE)
1801 mq_fdclose(td, i, fp);
1802 FILEDESC_XUNLOCK(fdp);
1803 (void) closef(fp, td);
1804 FILEDESC_XLOCK(fdp);
1807 FILEDESC_XUNLOCK(fdp);
1811 * It is unsafe for set[ug]id processes to be started with file
1812 * descriptors 0..2 closed, as these descriptors are given implicit
1813 * significance in the Standard C library. fdcheckstd() will create a
1814 * descriptor referencing /dev/null for each of stdin, stdout, and
1815 * stderr that is not already open.
1818 fdcheckstd(struct thread *td)
1820 struct filedesc *fdp;
1821 register_t retval, save;
1822 int i, error, devnull;
1824 fdp = td->td_proc->p_fd;
1827 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1830 for (i = 0; i < 3; i++) {
1831 if (fdp->fd_ofiles[i] != NULL)
1834 save = td->td_retval[0];
1835 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1837 devnull = td->td_retval[0];
1838 KASSERT(devnull == i, ("oof, we didn't get our fd"));
1839 td->td_retval[0] = save;
1843 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1852 * Internal form of close. Decrement reference count on file structure.
1853 * Note: td may be NULL when closing a file that was being passed in a
1856 * XXXRW: Giant is not required for the caller, but often will be held; this
1857 * makes it moderately likely the Giant will be recursed in the VFS case.
1860 closef(struct file *fp, struct thread *td)
1864 struct filedesc_to_leader *fdtol;
1865 struct filedesc *fdp;
1868 * POSIX record locking dictates that any close releases ALL
1869 * locks owned by this process. This is handled by setting
1870 * a flag in the unlock to free ONLY locks obeying POSIX
1871 * semantics, and not to free BSD-style file locks.
1872 * If the descriptor was in a message, POSIX-style locks
1873 * aren't passed with the descriptor, and the thread pointer
1874 * will be NULL. Callers should be careful only to pass a
1875 * NULL thread pointer when there really is no owning
1876 * context that might have locks, or the locks will be
1879 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1883 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1884 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1885 lf.l_whence = SEEK_SET;
1888 lf.l_type = F_UNLCK;
1889 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1890 F_UNLCK, &lf, F_POSIX);
1892 fdtol = td->td_proc->p_fdtol;
1893 if (fdtol != NULL) {
1895 * Handle special case where file descriptor table is
1896 * shared between multiple process leaders.
1898 fdp = td->td_proc->p_fd;
1899 FILEDESC_XLOCK(fdp);
1900 for (fdtol = fdtol->fdl_next;
1901 fdtol != td->td_proc->p_fdtol;
1902 fdtol = fdtol->fdl_next) {
1903 if ((fdtol->fdl_leader->p_flag &
1906 fdtol->fdl_holdcount++;
1907 FILEDESC_XUNLOCK(fdp);
1908 lf.l_whence = SEEK_SET;
1911 lf.l_type = F_UNLCK;
1913 (void) VOP_ADVLOCK(vp,
1914 (caddr_t)fdtol->fdl_leader,
1915 F_UNLCK, &lf, F_POSIX);
1916 FILEDESC_XLOCK(fdp);
1917 fdtol->fdl_holdcount--;
1918 if (fdtol->fdl_holdcount == 0 &&
1919 fdtol->fdl_wakeup != 0) {
1920 fdtol->fdl_wakeup = 0;
1924 FILEDESC_XUNLOCK(fdp);
1926 VFS_UNLOCK_GIANT(vfslocked);
1928 return (fdrop(fp, td));
1932 * Extract the file pointer associated with the specified descriptor for the
1933 * current user process.
1935 * If the descriptor doesn't exist, EBADF is returned.
1937 * If the descriptor exists but doesn't match 'flags' then return EBADF for
1938 * read attempts and EINVAL for write attempts.
1940 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1941 * It should be dropped with fdrop(). If it is not set, then the refcount
1942 * will not be bumped however the thread's filedesc struct will be returned
1943 * locked (for fgetsock).
1945 * If an error occured the non-zero error is returned and *fpp is set to
1946 * NULL. Otherwise *fpp is set and zero is returned.
1949 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1951 struct filedesc *fdp;
1955 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1957 FILEDESC_SLOCK(fdp);
1958 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1959 FILEDESC_SUNLOCK(fdp);
1964 * FREAD and FWRITE failure return EBADF as per POSIX.
1966 * Only one flag, or 0, may be specified.
1968 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1969 FILEDESC_SUNLOCK(fdp);
1972 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1973 FILEDESC_SUNLOCK(fdp);
1978 FILEDESC_SUNLOCK(fdp);
1985 fget(struct thread *td, int fd, struct file **fpp)
1988 return(_fget(td, fd, fpp, 0, 1));
1992 fget_read(struct thread *td, int fd, struct file **fpp)
1995 return(_fget(td, fd, fpp, FREAD, 1));
1999 fget_write(struct thread *td, int fd, struct file **fpp)
2002 return(_fget(td, fd, fpp, FWRITE, 1));
2006 * Like fget() but loads the underlying vnode, or returns an error if the
2007 * descriptor does not represent a vnode. Note that pipes use vnodes but
2008 * never have VM objects. The returned vnode will be vref()'d.
2010 * XXX: what about the unused flags ?
2013 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2019 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2021 if (fp->f_vnode == NULL) {
2027 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2032 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2035 return (_fgetvp(td, fd, vpp, 0));
2039 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2042 return (_fgetvp(td, fd, vpp, FREAD));
2047 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2050 return (_fgetvp(td, fd, vpp, FWRITE));
2055 * Like fget() but loads the underlying socket, or returns an error if the
2056 * descriptor does not represent a socket.
2058 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2061 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2062 * on their file descriptor reference to prevent the socket from being free'd
2066 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2076 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2078 if (fp->f_type != DTYPE_SOCKET) {
2083 *fflagp = fp->f_flag;
2088 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2093 * Drop the reference count on the socket and XXX release the SX lock in the
2094 * future. The last reference closes the socket.
2096 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2099 fputsock(struct socket *so)
2109 fdrop(struct file *fp, struct thread *td)
2113 return (fdrop_locked(fp, td));
2117 * Drop reference on struct file passed in, may call closef if the
2118 * reference hits zero.
2119 * Expects struct file locked, and will unlock it.
2122 fdrop_locked(struct file *fp, struct thread *td)
2126 FILE_LOCK_ASSERT(fp, MA_OWNED);
2128 if (--fp->f_count > 0) {
2134 * We might have just dropped the last reference to a file
2135 * object that is for a UNIX domain socket whose message
2136 * buffers are being examined in unp_gc(). If that is the
2137 * case, FWAIT will be set in f_gcflag and we need to wait for
2138 * unp_gc() to finish its scan.
2140 while (fp->f_gcflag & FWAIT)
2141 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2143 /* We have the last ref so we can proceed without the file lock. */
2145 if (fp->f_count < 0)
2146 panic("fdrop: count < 0");
2147 if (fp->f_ops != &badfileops)
2148 error = fo_close(fp, td);
2152 sx_xlock(&filelist_lock);
2153 LIST_REMOVE(fp, f_list);
2155 sx_xunlock(&filelist_lock);
2157 uma_zfree(file_zone, fp);
2163 * Apply an advisory lock on a file descriptor.
2165 * Just attempt to get a record lock of the requested type on the entire file
2166 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2168 #ifndef _SYS_SYSPROTO_H_
2176 flock(struct thread *td, struct flock_args *uap)
2183 if ((error = fget(td, uap->fd, &fp)) != 0)
2185 if (fp->f_type != DTYPE_VNODE) {
2187 return (EOPNOTSUPP);
2192 lf.l_whence = SEEK_SET;
2195 if (uap->how & LOCK_UN) {
2196 lf.l_type = F_UNLCK;
2198 fp->f_flag &= ~FHASLOCK;
2200 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2203 if (uap->how & LOCK_EX)
2204 lf.l_type = F_WRLCK;
2205 else if (uap->how & LOCK_SH)
2206 lf.l_type = F_RDLCK;
2212 fp->f_flag |= FHASLOCK;
2214 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2215 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2222 * Duplicate the specified descriptor to a free descriptor.
2225 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2231 * If the to-be-dup'd fd number is greater than the allowed number
2232 * of file descriptors, or the fd to be dup'd has already been
2233 * closed, then reject.
2235 FILEDESC_XLOCK(fdp);
2236 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2237 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2238 FILEDESC_XUNLOCK(fdp);
2243 * There are two cases of interest here.
2245 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2247 * For ENXIO steal away the file structure from (dfd) and store it in
2248 * (indx). (dfd) is effectively closed by this operation.
2250 * Any other error code is just returned.
2255 * Check that the mode the file is being opened for is a
2256 * subset of the mode of the existing descriptor.
2259 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2261 FILEDESC_XUNLOCK(fdp);
2264 fp = fdp->fd_ofiles[indx];
2265 fdp->fd_ofiles[indx] = wfp;
2266 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2271 FILEDESC_XUNLOCK(fdp);
2274 * We now own the reference to fp that the ofiles[]
2275 * array used to own. Release it.
2282 * Steal away the file pointer from dfd and stuff it into indx.
2284 fp = fdp->fd_ofiles[indx];
2285 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2286 fdp->fd_ofiles[dfd] = NULL;
2287 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2288 fdp->fd_ofileflags[dfd] = 0;
2292 FILEDESC_XUNLOCK(fdp);
2295 * We now own the reference to fp that the ofiles[] array
2296 * used to own. Release it.
2303 FILEDESC_XUNLOCK(fdp);
2310 * Scan all active processes to see if any of them have a current or root
2311 * directory of `olddp'. If so, replace them with the new mount point.
2314 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2316 struct filedesc *fdp;
2320 if (vrefcnt(olddp) == 1)
2322 sx_slock(&allproc_lock);
2323 FOREACH_PROC_IN_SYSTEM(p) {
2328 FILEDESC_XLOCK(fdp);
2329 if (fdp->fd_cdir == olddp) {
2331 fdp->fd_cdir = newdp;
2334 if (fdp->fd_rdir == olddp) {
2336 fdp->fd_rdir = newdp;
2339 FILEDESC_XUNLOCK(fdp);
2344 sx_sunlock(&allproc_lock);
2345 if (rootvnode == olddp) {
2352 struct filedesc_to_leader *
2353 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2355 struct filedesc_to_leader *fdtol;
2357 MALLOC(fdtol, struct filedesc_to_leader *,
2358 sizeof(struct filedesc_to_leader),
2359 M_FILEDESC_TO_LEADER,
2361 fdtol->fdl_refcount = 1;
2362 fdtol->fdl_holdcount = 0;
2363 fdtol->fdl_wakeup = 0;
2364 fdtol->fdl_leader = leader;
2366 FILEDESC_XLOCK(fdp);
2367 fdtol->fdl_next = old->fdl_next;
2368 fdtol->fdl_prev = old;
2369 old->fdl_next = fdtol;
2370 fdtol->fdl_next->fdl_prev = fdtol;
2371 FILEDESC_XUNLOCK(fdp);
2373 fdtol->fdl_next = fdtol;
2374 fdtol->fdl_prev = fdtol;
2380 * Get file structures.
2383 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2386 struct filedesc *fdp;
2392 * Note: because the number of file descriptors is calculated
2393 * in different ways for sizing vs returning the data,
2394 * there is information leakage from the first loop. However,
2395 * it is of a similar order of magnitude to the leakage from
2396 * global system statistics such as kern.openfiles.
2398 error = sysctl_wire_old_buffer(req, 0);
2401 if (req->oldptr == NULL) {
2402 n = 16; /* A slight overestimate. */
2403 sx_slock(&filelist_lock);
2404 LIST_FOREACH(fp, &filehead, f_list) {
2406 * We should grab the lock, but this is an
2407 * estimate, so does it really matter?
2409 /* mtx_lock(fp->f_mtxp); */
2411 /* mtx_unlock(f->f_mtxp); */
2413 sx_sunlock(&filelist_lock);
2414 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2417 bzero(&xf, sizeof(xf));
2418 xf.xf_size = sizeof(xf);
2419 sx_slock(&allproc_lock);
2420 FOREACH_PROC_IN_SYSTEM(p) {
2421 if (p->p_state == PRS_NEW)
2424 if (p_cansee(req->td, p) != 0) {
2428 xf.xf_pid = p->p_pid;
2429 xf.xf_uid = p->p_ucred->cr_uid;
2434 FILEDESC_SLOCK(fdp);
2435 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2436 if ((fp = fdp->fd_ofiles[n]) == NULL)
2440 xf.xf_data = fp->f_data;
2441 xf.xf_vnode = fp->f_vnode;
2442 xf.xf_type = fp->f_type;
2443 xf.xf_count = fp->f_count;
2444 xf.xf_msgcount = fp->f_msgcount;
2445 xf.xf_offset = fp->f_offset;
2446 xf.xf_flag = fp->f_flag;
2447 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2451 FILEDESC_SUNLOCK(fdp);
2456 sx_sunlock(&allproc_lock);
2460 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2461 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2465 * For the purposes of debugging, generate a human-readable string for the
2469 file_type_to_name(short type)
2495 * For the purposes of debugging, identify a process (if any, perhaps one of
2496 * many) that references the passed file in its file descriptor array. Return
2499 static struct proc *
2500 file_to_first_proc(struct file *fp)
2502 struct filedesc *fdp;
2506 FOREACH_PROC_IN_SYSTEM(p) {
2507 if (p->p_state == PRS_NEW)
2512 for (n = 0; n < fdp->fd_nfiles; n++) {
2513 if (fp == fdp->fd_ofiles[n])
2521 db_print_file(struct file *fp, int header)
2526 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
2527 "File", "Type", "Data", "Flag", "GCFl", "Count",
2528 "MCount", "Vnode", "FPID", "FCmd");
2529 p = file_to_first_proc(fp);
2530 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2531 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2532 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2533 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2536 DB_SHOW_COMMAND(file, db_show_file)
2541 db_printf("usage: show file <addr>\n");
2544 fp = (struct file *)addr;
2545 db_print_file(fp, 1);
2548 DB_SHOW_COMMAND(files, db_show_files)
2554 LIST_FOREACH(fp, &filehead, f_list) {
2555 db_print_file(fp, header);
2561 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2562 &maxfilesperproc, 0, "Maximum files allowed open per process");
2564 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2565 &maxfiles, 0, "Maximum number of files");
2567 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2568 &openfiles, 0, "System-wide number of open files");
2572 filelistinit(void *dummy)
2575 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2576 NULL, NULL, UMA_ALIGN_PTR, 0);
2577 sx_init(&filelist_lock, "filelist lock");
2578 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2579 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2581 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2583 /*-------------------------------------------------------------------*/
2586 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2593 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2600 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2607 badfo_kqfilter(struct file *fp, struct knote *kn)
2614 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2621 badfo_close(struct file *fp, struct thread *td)
2627 struct fileops badfileops = {
2628 .fo_read = badfo_readwrite,
2629 .fo_write = badfo_readwrite,
2630 .fo_ioctl = badfo_ioctl,
2631 .fo_poll = badfo_poll,
2632 .fo_kqfilter = badfo_kqfilter,
2633 .fo_stat = badfo_stat,
2634 .fo_close = badfo_close,
2638 /*-------------------------------------------------------------------*/
2641 * File Descriptor pseudo-device driver (/dev/fd/).
2643 * Opening minor device N dup()s the file (if any) connected to file
2644 * descriptor N belonging to the calling process. Note that this driver
2645 * consists of only the ``open()'' routine, because all subsequent
2646 * references to this file will be direct to the other driver.
2648 * XXX: we could give this one a cloning event handler if necessary.
2653 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2657 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2658 * the file descriptor being sought for duplication. The error
2659 * return ensures that the vnode for this device will be released
2660 * by vn_open. Open will detect this special error and take the
2661 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2662 * will simply report the error.
2664 td->td_dupfd = dev2unit(dev);
2668 static struct cdevsw fildesc_cdevsw = {
2669 .d_version = D_VERSION,
2670 .d_flags = D_NEEDGIANT,
2676 fildesc_drvinit(void *unused)
2680 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2681 make_dev_alias(dev, "stdin");
2682 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2683 make_dev_alias(dev, "stdout");
2684 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2685 make_dev_alias(dev, "stderr");
2688 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)