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 /* we've allocated a descriptor which we won't use */
671 if (fdp->fd_ofiles[new] == NULL)
673 FILEDESC_XUNLOCK(fdp);
678 ("new fd is same as old"));
681 * Save info on the descriptor being overwritten. We cannot close
682 * it without introducing an ownership race for the slot, since we
683 * need to drop the filedesc lock to call closef().
685 * XXX this duplicates parts of close().
687 delfp = fdp->fd_ofiles[new];
690 if (td->td_proc->p_fdtol != NULL) {
692 * Ask fdfree() to sleep to ensure that all relevant
693 * process leaders can be traversed in closef().
695 fdp->fd_holdleaderscount++;
701 * Duplicate the source descriptor
703 fdp->fd_ofiles[new] = fp;
704 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
705 if (new > fdp->fd_lastfile)
706 fdp->fd_lastfile = new;
710 * If we dup'd over a valid file, we now own the reference to it
711 * and must dispose of it using closef() semantics (as if a
712 * close() were performed on it).
714 * XXX this duplicates parts of close().
717 knote_fdclose(td, new);
718 if (delfp->f_type == DTYPE_MQUEUE)
719 mq_fdclose(td, new, delfp);
720 FILEDESC_XUNLOCK(fdp);
721 (void) closef(delfp, td);
724 fdp->fd_holdleaderscount--;
725 if (fdp->fd_holdleaderscount == 0 &&
726 fdp->fd_holdleaderswakeup != 0) {
727 fdp->fd_holdleaderswakeup = 0;
728 wakeup(&fdp->fd_holdleaderscount);
730 FILEDESC_XUNLOCK(fdp);
733 FILEDESC_XUNLOCK(fdp);
739 * If sigio is on the list associated with a process or process group,
740 * disable signalling from the device, remove sigio from the list and
744 funsetown(struct sigio **sigiop)
754 *(sigio->sio_myref) = NULL;
755 if ((sigio)->sio_pgid < 0) {
756 struct pgrp *pg = (sigio)->sio_pgrp;
758 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
762 struct proc *p = (sigio)->sio_proc;
764 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
769 crfree(sigio->sio_ucred);
770 FREE(sigio, M_SIGIO);
774 * Free a list of sigio structures.
775 * We only need to lock the SIGIO_LOCK because we have made ourselves
776 * inaccessible to callers of fsetown and therefore do not need to lock
777 * the proc or pgrp struct for the list manipulation.
780 funsetownlst(struct sigiolst *sigiolst)
786 sigio = SLIST_FIRST(sigiolst);
793 * Every entry of the list should belong
794 * to a single proc or pgrp.
796 if (sigio->sio_pgid < 0) {
797 pg = sigio->sio_pgrp;
798 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
799 } else /* if (sigio->sio_pgid > 0) */ {
801 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
805 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
806 *(sigio->sio_myref) = NULL;
808 KASSERT(sigio->sio_pgid < 0,
809 ("Proc sigio in pgrp sigio list"));
810 KASSERT(sigio->sio_pgrp == pg,
811 ("Bogus pgrp in sigio list"));
813 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
816 } else /* if (p != NULL) */ {
817 KASSERT(sigio->sio_pgid > 0,
818 ("Pgrp sigio in proc sigio list"));
819 KASSERT(sigio->sio_proc == p,
820 ("Bogus proc in sigio list"));
822 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
827 crfree(sigio->sio_ucred);
828 FREE(sigio, M_SIGIO);
835 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
837 * After permission checking, add a sigio structure to the sigio list for
838 * the process or process group.
841 fsetown(pid_t pgid, struct sigio **sigiop)
855 /* Allocate and fill in the new sigio out of locks. */
856 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
857 sigio->sio_pgid = pgid;
858 sigio->sio_ucred = crhold(curthread->td_ucred);
859 sigio->sio_myref = sigiop;
861 sx_slock(&proctree_lock);
870 * Policy - Don't allow a process to FSETOWN a process
871 * in another session.
873 * Remove this test to allow maximum flexibility or
874 * restrict FSETOWN to the current process or process
875 * group for maximum safety.
878 if (proc->p_session != curthread->td_proc->p_session) {
884 } else /* if (pgid < 0) */ {
885 pgrp = pgfind(-pgid);
893 * Policy - Don't allow a process to FSETOWN a process
894 * in another session.
896 * Remove this test to allow maximum flexibility or
897 * restrict FSETOWN to the current process or process
898 * group for maximum safety.
900 if (pgrp->pg_session != curthread->td_proc->p_session) {
911 * Since funsetownlst() is called without the proctree
912 * locked, we need to check for P_WEXIT.
913 * XXX: is ESRCH correct?
915 if ((proc->p_flag & P_WEXIT) != 0) {
920 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
921 sigio->sio_proc = proc;
925 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
926 sigio->sio_pgrp = pgrp;
929 sx_sunlock(&proctree_lock);
936 sx_sunlock(&proctree_lock);
937 crfree(sigio->sio_ucred);
938 FREE(sigio, M_SIGIO);
943 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
947 struct sigio **sigiop;
952 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
958 * Close a file descriptor.
960 #ifndef _SYS_SYSPROTO_H_
969 struct close_args *uap;
972 return (kern_close(td, uap->fd));
980 struct filedesc *fdp;
987 fdp = td->td_proc->p_fd;
989 AUDIT_SYSCLOSE(td, fd);
992 if ((unsigned)fd >= fdp->fd_nfiles ||
993 (fp = fdp->fd_ofiles[fd]) == NULL) {
994 FILEDESC_XUNLOCK(fdp);
997 fdp->fd_ofiles[fd] = NULL;
998 fdp->fd_ofileflags[fd] = 0;
1000 if (td->td_proc->p_fdtol != NULL) {
1002 * Ask fdfree() to sleep to ensure that all relevant
1003 * process leaders can be traversed in closef().
1005 fdp->fd_holdleaderscount++;
1010 * We now hold the fp reference that used to be owned by the
1011 * descriptor array. We have to unlock the FILEDESC *AFTER*
1012 * knote_fdclose to prevent a race of the fd getting opened, a knote
1013 * added, and deleteing a knote for the new fd.
1015 knote_fdclose(td, fd);
1016 if (fp->f_type == DTYPE_MQUEUE)
1017 mq_fdclose(td, fd, fp);
1018 FILEDESC_XUNLOCK(fdp);
1020 error = closef(fp, td);
1022 FILEDESC_XLOCK(fdp);
1023 fdp->fd_holdleaderscount--;
1024 if (fdp->fd_holdleaderscount == 0 &&
1025 fdp->fd_holdleaderswakeup != 0) {
1026 fdp->fd_holdleaderswakeup = 0;
1027 wakeup(&fdp->fd_holdleaderscount);
1029 FILEDESC_XUNLOCK(fdp);
1034 #if defined(COMPAT_43)
1036 * Return status information about a file descriptor.
1038 #ifndef _SYS_SYSPROTO_H_
1039 struct ofstat_args {
1046 ofstat(struct thread *td, struct ofstat_args *uap)
1052 error = kern_fstat(td, uap->fd, &ub);
1055 error = copyout(&oub, uap->sb, sizeof(oub));
1059 #endif /* COMPAT_43 */
1062 * Return status information about a file descriptor.
1064 #ifndef _SYS_SYSPROTO_H_
1072 fstat(struct thread *td, struct fstat_args *uap)
1077 error = kern_fstat(td, uap->fd, &ub);
1079 error = copyout(&ub, uap->sb, sizeof(ub));
1084 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1091 if ((error = fget(td, fd, &fp)) != 0)
1094 AUDIT_ARG(file, td->td_proc, fp);
1096 error = fo_stat(fp, sbp, td->td_ucred, td);
1102 * Return status information about a file descriptor.
1104 #ifndef _SYS_SYSPROTO_H_
1105 struct nfstat_args {
1112 nfstat(struct thread *td, struct nfstat_args *uap)
1118 error = kern_fstat(td, uap->fd, &ub);
1120 cvtnstat(&ub, &nub);
1121 error = copyout(&nub, uap->sb, sizeof(nub));
1127 * Return pathconf information about a file descriptor.
1129 #ifndef _SYS_SYSPROTO_H_
1130 struct fpathconf_args {
1137 fpathconf(struct thread *td, struct fpathconf_args *uap)
1143 if ((error = fget(td, uap->fd, &fp)) != 0)
1146 /* If asynchronous I/O is available, it works for all descriptors. */
1147 if (uap->name == _PC_ASYNC_IO) {
1148 td->td_retval[0] = async_io_version;
1154 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1155 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1156 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1157 VOP_UNLOCK(vp, 0, td);
1158 VFS_UNLOCK_GIANT(vfslocked);
1159 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1160 if (uap->name != _PC_PIPE_BUF) {
1163 td->td_retval[0] = PIPE_BUF;
1175 * Grow the file table to accomodate (at least) nfd descriptors. This may
1176 * block and drop the filedesc lock, but it will reacquire it before
1180 fdgrowtable(struct filedesc *fdp, int nfd)
1182 struct file **ntable;
1184 int nnfiles, onfiles;
1187 FILEDESC_XLOCK_ASSERT(fdp);
1189 KASSERT(fdp->fd_nfiles > 0,
1190 ("zero-length file table"));
1192 /* compute the size of the new table */
1193 onfiles = fdp->fd_nfiles;
1194 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1195 if (nnfiles <= onfiles)
1196 /* the table is already large enough */
1199 /* allocate a new table and (if required) new bitmaps */
1200 FILEDESC_XUNLOCK(fdp);
1201 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1202 M_FILEDESC, M_ZERO | M_WAITOK);
1203 nfileflags = (char *)&ntable[nnfiles];
1204 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1205 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1206 M_FILEDESC, M_ZERO | M_WAITOK);
1209 FILEDESC_XLOCK(fdp);
1212 * We now have new tables ready to go. Since we dropped the
1213 * filedesc lock to call malloc(), watch out for a race.
1215 onfiles = fdp->fd_nfiles;
1216 if (onfiles >= nnfiles) {
1217 /* we lost the race, but that's OK */
1218 free(ntable, M_FILEDESC);
1220 free(nmap, M_FILEDESC);
1223 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1224 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1225 if (onfiles > NDFILE)
1226 free(fdp->fd_ofiles, M_FILEDESC);
1227 fdp->fd_ofiles = ntable;
1228 fdp->fd_ofileflags = nfileflags;
1229 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1230 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1231 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1232 free(fdp->fd_map, M_FILEDESC);
1235 fdp->fd_nfiles = nnfiles;
1239 * Allocate a file descriptor for the process.
1242 fdalloc(struct thread *td, int minfd, int *result)
1244 struct proc *p = td->td_proc;
1245 struct filedesc *fdp = p->p_fd;
1248 FILEDESC_XLOCK_ASSERT(fdp);
1250 if (fdp->fd_freefile > minfd)
1251 minfd = fdp->fd_freefile;
1254 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1258 * Search the bitmap for a free descriptor. If none is found, try
1259 * to grow the file table. Keep at it until we either get a file
1260 * descriptor or run into process or system limits; fdgrowtable()
1261 * may drop the filedesc lock, so we're in a race.
1264 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1267 if (fd < fdp->fd_nfiles)
1269 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1273 * Perform some sanity checks, then mark the file descriptor as
1274 * used and return it to the caller.
1276 KASSERT(!fdisused(fdp, fd),
1277 ("fd_first_free() returned non-free descriptor"));
1278 KASSERT(fdp->fd_ofiles[fd] == NULL,
1279 ("free descriptor isn't"));
1280 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1287 * Check to see whether n user file descriptors are available to the process
1291 fdavail(struct thread *td, int n)
1293 struct proc *p = td->td_proc;
1294 struct filedesc *fdp = td->td_proc->p_fd;
1298 FILEDESC_LOCK_ASSERT(fdp);
1301 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1303 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1305 last = min(fdp->fd_nfiles, lim);
1306 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1307 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1308 if (*fpp == NULL && --n <= 0)
1315 * Create a new open file structure and allocate a file decriptor for the
1316 * process that refers to it. We add one reference to the file for the
1317 * descriptor table and one reference for resultfp. This is to prevent us
1318 * being preempted and the entry in the descriptor table closed after we
1319 * release the FILEDESC lock.
1322 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1324 struct proc *p = td->td_proc;
1325 struct file *fp, *fq;
1327 int maxuserfiles = maxfiles - (maxfiles / 20);
1328 static struct timeval lastfail;
1331 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1332 sx_xlock(&filelist_lock);
1334 if ((openfiles >= maxuserfiles &&
1335 priv_check_cred(td->td_ucred, PRIV_MAXFILES, SUSER_RUID) != 0) ||
1336 openfiles >= maxfiles) {
1337 if (ppsratecheck(&lastfail, &curfail, 1)) {
1338 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1339 td->td_ucred->cr_ruid);
1341 sx_xunlock(&filelist_lock);
1342 uma_zfree(file_zone, fp);
1348 * If the process has file descriptor zero open, add the new file
1349 * descriptor to the list of open files at that point, otherwise
1350 * put it at the front of the list of open files.
1352 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1356 fp->f_cred = crhold(td->td_ucred);
1357 fp->f_ops = &badfileops;
1360 FILEDESC_XLOCK(p->p_fd);
1361 if ((fq = p->p_fd->fd_ofiles[0])) {
1362 LIST_INSERT_AFTER(fq, fp, f_list);
1364 LIST_INSERT_HEAD(&filehead, fp, f_list);
1366 sx_xunlock(&filelist_lock);
1367 if ((error = fdalloc(td, 0, &i))) {
1368 FILEDESC_XUNLOCK(p->p_fd);
1374 p->p_fd->fd_ofiles[i] = fp;
1375 FILEDESC_XUNLOCK(p->p_fd);
1384 * Build a new filedesc structure from another.
1385 * Copy the current, root, and jail root vnode references.
1388 fdinit(struct filedesc *fdp)
1390 struct filedesc0 *newfdp;
1392 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1393 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1395 FILEDESC_XLOCK(fdp);
1396 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1397 if (newfdp->fd_fd.fd_cdir)
1398 VREF(newfdp->fd_fd.fd_cdir);
1399 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1400 if (newfdp->fd_fd.fd_rdir)
1401 VREF(newfdp->fd_fd.fd_rdir);
1402 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1403 if (newfdp->fd_fd.fd_jdir)
1404 VREF(newfdp->fd_fd.fd_jdir);
1405 FILEDESC_XUNLOCK(fdp);
1408 /* Create the file descriptor table. */
1409 newfdp->fd_fd.fd_refcnt = 1;
1410 newfdp->fd_fd.fd_holdcnt = 1;
1411 newfdp->fd_fd.fd_cmask = CMASK;
1412 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1413 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1414 newfdp->fd_fd.fd_nfiles = NDFILE;
1415 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1416 newfdp->fd_fd.fd_lastfile = -1;
1417 return (&newfdp->fd_fd);
1420 static struct filedesc *
1421 fdhold(struct proc *p)
1423 struct filedesc *fdp;
1425 mtx_lock(&fdesc_mtx);
1429 mtx_unlock(&fdesc_mtx);
1434 fddrop(struct filedesc *fdp)
1438 mtx_lock(&fdesc_mtx);
1439 i = --fdp->fd_holdcnt;
1440 mtx_unlock(&fdesc_mtx);
1444 FILEDESC_LOCK_DESTROY(fdp);
1445 FREE(fdp, M_FILEDESC);
1449 * Share a filedesc structure.
1452 fdshare(struct filedesc *fdp)
1455 FILEDESC_XLOCK(fdp);
1457 FILEDESC_XUNLOCK(fdp);
1462 * Unshare a filedesc structure, if necessary by making a copy
1465 fdunshare(struct proc *p, struct thread *td)
1468 FILEDESC_XLOCK(p->p_fd);
1469 if (p->p_fd->fd_refcnt > 1) {
1470 struct filedesc *tmp;
1472 FILEDESC_XUNLOCK(p->p_fd);
1473 tmp = fdcopy(p->p_fd);
1477 FILEDESC_XUNLOCK(p->p_fd);
1481 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1482 * this is to ease callers, not catch errors.
1485 fdcopy(struct filedesc *fdp)
1487 struct filedesc *newfdp;
1490 /* Certain daemons might not have file descriptors. */
1494 newfdp = fdinit(fdp);
1495 FILEDESC_SLOCK(fdp);
1496 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1497 FILEDESC_SUNLOCK(fdp);
1498 FILEDESC_XLOCK(newfdp);
1499 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1500 FILEDESC_XUNLOCK(newfdp);
1501 FILEDESC_SLOCK(fdp);
1503 /* copy everything except kqueue descriptors */
1504 newfdp->fd_freefile = -1;
1505 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1506 if (fdisused(fdp, i) &&
1507 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1508 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1509 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1510 fhold(newfdp->fd_ofiles[i]);
1511 newfdp->fd_lastfile = i;
1513 if (newfdp->fd_freefile == -1)
1514 newfdp->fd_freefile = i;
1517 FILEDESC_SUNLOCK(fdp);
1518 FILEDESC_XLOCK(newfdp);
1519 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1520 if (newfdp->fd_ofiles[i] != NULL)
1522 FILEDESC_XUNLOCK(newfdp);
1523 FILEDESC_SLOCK(fdp);
1524 if (newfdp->fd_freefile == -1)
1525 newfdp->fd_freefile = i;
1526 newfdp->fd_cmask = fdp->fd_cmask;
1527 FILEDESC_SUNLOCK(fdp);
1532 * Release a filedesc structure.
1535 fdfree(struct thread *td)
1537 struct filedesc *fdp;
1540 struct filedesc_to_leader *fdtol;
1542 struct vnode *cdir, *jdir, *rdir, *vp;
1545 /* Certain daemons might not have file descriptors. */
1546 fdp = td->td_proc->p_fd;
1550 /* Check for special need to clear POSIX style locks */
1551 fdtol = td->td_proc->p_fdtol;
1552 if (fdtol != NULL) {
1553 FILEDESC_XLOCK(fdp);
1554 KASSERT(fdtol->fdl_refcount > 0,
1555 ("filedesc_to_refcount botch: fdl_refcount=%d",
1556 fdtol->fdl_refcount));
1557 if (fdtol->fdl_refcount == 1 &&
1558 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1559 for (i = 0, fpp = fdp->fd_ofiles;
1560 i <= fdp->fd_lastfile;
1563 (*fpp)->f_type != DTYPE_VNODE)
1567 FILEDESC_XUNLOCK(fdp);
1568 lf.l_whence = SEEK_SET;
1571 lf.l_type = F_UNLCK;
1573 locked = VFS_LOCK_GIANT(vp->v_mount);
1574 (void) VOP_ADVLOCK(vp,
1575 (caddr_t)td->td_proc->
1580 VFS_UNLOCK_GIANT(locked);
1581 FILEDESC_XLOCK(fdp);
1583 fpp = fdp->fd_ofiles + i;
1587 if (fdtol->fdl_refcount == 1) {
1588 if (fdp->fd_holdleaderscount > 0 &&
1589 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1591 * close() or do_dup() has cleared a reference
1592 * in a shared file descriptor table.
1594 fdp->fd_holdleaderswakeup = 1;
1595 sx_sleep(&fdp->fd_holdleaderscount,
1596 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1599 if (fdtol->fdl_holdcount > 0) {
1601 * Ensure that fdtol->fdl_leader remains
1602 * valid in closef().
1604 fdtol->fdl_wakeup = 1;
1605 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1610 fdtol->fdl_refcount--;
1611 if (fdtol->fdl_refcount == 0 &&
1612 fdtol->fdl_holdcount == 0) {
1613 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1614 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1617 td->td_proc->p_fdtol = NULL;
1618 FILEDESC_XUNLOCK(fdp);
1620 FREE(fdtol, M_FILEDESC_TO_LEADER);
1622 FILEDESC_XLOCK(fdp);
1623 i = --fdp->fd_refcnt;
1624 FILEDESC_XUNLOCK(fdp);
1628 * We are the last reference to the structure, so we can
1629 * safely assume it will not change out from under us.
1631 fpp = fdp->fd_ofiles;
1632 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1634 (void) closef(*fpp, td);
1636 FILEDESC_XLOCK(fdp);
1638 /* XXX This should happen earlier. */
1639 mtx_lock(&fdesc_mtx);
1640 td->td_proc->p_fd = NULL;
1641 mtx_unlock(&fdesc_mtx);
1643 if (fdp->fd_nfiles > NDFILE)
1644 FREE(fdp->fd_ofiles, M_FILEDESC);
1645 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1646 FREE(fdp->fd_map, M_FILEDESC);
1650 cdir = fdp->fd_cdir;
1651 fdp->fd_cdir = NULL;
1652 rdir = fdp->fd_rdir;
1653 fdp->fd_rdir = NULL;
1654 jdir = fdp->fd_jdir;
1655 fdp->fd_jdir = NULL;
1656 FILEDESC_XUNLOCK(fdp);
1659 locked = VFS_LOCK_GIANT(cdir->v_mount);
1661 VFS_UNLOCK_GIANT(locked);
1664 locked = VFS_LOCK_GIANT(rdir->v_mount);
1666 VFS_UNLOCK_GIANT(locked);
1669 locked = VFS_LOCK_GIANT(jdir->v_mount);
1671 VFS_UNLOCK_GIANT(locked);
1678 * For setugid programs, we don't want to people to use that setugidness
1679 * to generate error messages which write to a file which otherwise would
1680 * otherwise be off-limits to the process. We check for filesystems where
1681 * the vnode can change out from under us after execve (like [lin]procfs).
1683 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1684 * sufficient. We also don't check for setugidness since we know we are.
1687 is_unsafe(struct file *fp)
1689 if (fp->f_type == DTYPE_VNODE) {
1690 struct vnode *vp = fp->f_vnode;
1692 if ((vp->v_vflag & VV_PROCDEP) != 0)
1699 * Make this setguid thing safe, if at all possible.
1702 setugidsafety(struct thread *td)
1704 struct filedesc *fdp;
1707 /* Certain daemons might not have file descriptors. */
1708 fdp = td->td_proc->p_fd;
1713 * Note: fdp->fd_ofiles may be reallocated out from under us while
1714 * we are blocked in a close. Be careful!
1716 FILEDESC_XLOCK(fdp);
1717 for (i = 0; i <= fdp->fd_lastfile; i++) {
1720 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1723 knote_fdclose(td, i);
1725 * NULL-out descriptor prior to close to avoid
1726 * a race while close blocks.
1728 fp = fdp->fd_ofiles[i];
1729 fdp->fd_ofiles[i] = NULL;
1730 fdp->fd_ofileflags[i] = 0;
1732 FILEDESC_XUNLOCK(fdp);
1733 (void) closef(fp, td);
1734 FILEDESC_XLOCK(fdp);
1737 FILEDESC_XUNLOCK(fdp);
1741 * If a specific file object occupies a specific file descriptor, close the
1742 * file descriptor entry and drop a reference on the file object. This is a
1743 * convenience function to handle a subsequent error in a function that calls
1744 * falloc() that handles the race that another thread might have closed the
1745 * file descriptor out from under the thread creating the file object.
1748 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1751 FILEDESC_XLOCK(fdp);
1752 if (fdp->fd_ofiles[idx] == fp) {
1753 fdp->fd_ofiles[idx] = NULL;
1755 FILEDESC_XUNLOCK(fdp);
1758 FILEDESC_XUNLOCK(fdp);
1762 * Close any files on exec?
1765 fdcloseexec(struct thread *td)
1767 struct filedesc *fdp;
1770 /* Certain daemons might not have file descriptors. */
1771 fdp = td->td_proc->p_fd;
1775 FILEDESC_XLOCK(fdp);
1778 * We cannot cache fd_ofiles or fd_ofileflags since operations
1779 * may block and rip them out from under us.
1781 for (i = 0; i <= fdp->fd_lastfile; i++) {
1782 if (fdp->fd_ofiles[i] != NULL &&
1783 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1784 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1787 knote_fdclose(td, i);
1789 * NULL-out descriptor prior to close to avoid
1790 * a race while close blocks.
1792 fp = fdp->fd_ofiles[i];
1793 fdp->fd_ofiles[i] = NULL;
1794 fdp->fd_ofileflags[i] = 0;
1796 if (fp->f_type == DTYPE_MQUEUE)
1797 mq_fdclose(td, i, fp);
1798 FILEDESC_XUNLOCK(fdp);
1799 (void) closef(fp, td);
1800 FILEDESC_XLOCK(fdp);
1803 FILEDESC_XUNLOCK(fdp);
1807 * It is unsafe for set[ug]id processes to be started with file
1808 * descriptors 0..2 closed, as these descriptors are given implicit
1809 * significance in the Standard C library. fdcheckstd() will create a
1810 * descriptor referencing /dev/null for each of stdin, stdout, and
1811 * stderr that is not already open.
1814 fdcheckstd(struct thread *td)
1816 struct nameidata nd;
1817 struct filedesc *fdp;
1820 int fd, i, error, flags, devnull;
1822 fdp = td->td_proc->p_fd;
1825 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1828 for (i = 0; i < 3; i++) {
1829 if (fdp->fd_ofiles[i] != NULL)
1833 error = falloc(td, &fp, &fd);
1836 /* Note extra ref on `fp' held for us by falloc(). */
1837 KASSERT(fd == i, ("oof, we didn't get our fd"));
1838 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1840 flags = FREAD | FWRITE;
1841 error = vn_open(&nd, &flags, 0, fd);
1844 * Someone may have closed the entry in the
1845 * file descriptor table, so check it hasn't
1846 * changed before dropping the reference
1849 FILEDESC_XLOCK(fdp);
1850 KASSERT(fdp->fd_ofiles[fd] == fp,
1851 ("table not shared, how did it change?"));
1852 fdp->fd_ofiles[fd] = NULL;
1854 FILEDESC_XUNLOCK(fdp);
1859 vfslocked = NDHASGIANT(&nd);
1860 NDFREE(&nd, NDF_ONLY_PNBUF);
1863 fp->f_vnode = nd.ni_vp;
1864 if (fp->f_data == NULL)
1865 fp->f_data = nd.ni_vp;
1866 fp->f_type = DTYPE_VNODE;
1867 if (fp->f_ops == &badfileops)
1870 VOP_UNLOCK(nd.ni_vp, 0, td);
1871 VFS_UNLOCK_GIANT(vfslocked);
1875 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1884 * Internal form of close. Decrement reference count on file structure.
1885 * Note: td may be NULL when closing a file that was being passed in a
1888 * XXXRW: Giant is not required for the caller, but often will be held; this
1889 * makes it moderately likely the Giant will be recursed in the VFS case.
1892 closef(struct file *fp, struct thread *td)
1896 struct filedesc_to_leader *fdtol;
1897 struct filedesc *fdp;
1900 * POSIX record locking dictates that any close releases ALL
1901 * locks owned by this process. This is handled by setting
1902 * a flag in the unlock to free ONLY locks obeying POSIX
1903 * semantics, and not to free BSD-style file locks.
1904 * If the descriptor was in a message, POSIX-style locks
1905 * aren't passed with the descriptor, and the thread pointer
1906 * will be NULL. Callers should be careful only to pass a
1907 * NULL thread pointer when there really is no owning
1908 * context that might have locks, or the locks will be
1911 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1915 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1916 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1917 lf.l_whence = SEEK_SET;
1920 lf.l_type = F_UNLCK;
1921 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1922 F_UNLCK, &lf, F_POSIX);
1924 fdtol = td->td_proc->p_fdtol;
1925 if (fdtol != NULL) {
1927 * Handle special case where file descriptor table is
1928 * shared between multiple process leaders.
1930 fdp = td->td_proc->p_fd;
1931 FILEDESC_XLOCK(fdp);
1932 for (fdtol = fdtol->fdl_next;
1933 fdtol != td->td_proc->p_fdtol;
1934 fdtol = fdtol->fdl_next) {
1935 if ((fdtol->fdl_leader->p_flag &
1938 fdtol->fdl_holdcount++;
1939 FILEDESC_XUNLOCK(fdp);
1940 lf.l_whence = SEEK_SET;
1943 lf.l_type = F_UNLCK;
1945 (void) VOP_ADVLOCK(vp,
1946 (caddr_t)fdtol->fdl_leader,
1947 F_UNLCK, &lf, F_POSIX);
1948 FILEDESC_XLOCK(fdp);
1949 fdtol->fdl_holdcount--;
1950 if (fdtol->fdl_holdcount == 0 &&
1951 fdtol->fdl_wakeup != 0) {
1952 fdtol->fdl_wakeup = 0;
1956 FILEDESC_XUNLOCK(fdp);
1958 VFS_UNLOCK_GIANT(vfslocked);
1960 return (fdrop(fp, td));
1964 * Extract the file pointer associated with the specified descriptor for the
1965 * current user process.
1967 * If the descriptor doesn't exist, EBADF is returned.
1969 * If the descriptor exists but doesn't match 'flags' then return EBADF for
1970 * read attempts and EINVAL for write attempts.
1972 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1973 * It should be dropped with fdrop(). If it is not set, then the refcount
1974 * will not be bumped however the thread's filedesc struct will be returned
1975 * locked (for fgetsock).
1977 * If an error occured the non-zero error is returned and *fpp is set to
1978 * NULL. Otherwise *fpp is set and zero is returned.
1981 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1983 struct filedesc *fdp;
1987 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1989 FILEDESC_SLOCK(fdp);
1990 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1991 FILEDESC_SUNLOCK(fdp);
1996 * FREAD and FWRITE failure return EBADF as per POSIX.
1998 * Only one flag, or 0, may be specified.
2000 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
2001 FILEDESC_SUNLOCK(fdp);
2004 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2005 FILEDESC_SUNLOCK(fdp);
2010 FILEDESC_SUNLOCK(fdp);
2017 fget(struct thread *td, int fd, struct file **fpp)
2020 return(_fget(td, fd, fpp, 0, 1));
2024 fget_read(struct thread *td, int fd, struct file **fpp)
2027 return(_fget(td, fd, fpp, FREAD, 1));
2031 fget_write(struct thread *td, int fd, struct file **fpp)
2034 return(_fget(td, fd, fpp, FWRITE, 1));
2038 * Like fget() but loads the underlying vnode, or returns an error if the
2039 * descriptor does not represent a vnode. Note that pipes use vnodes but
2040 * never have VM objects. The returned vnode will be vref()'d.
2042 * XXX: what about the unused flags ?
2045 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2051 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2053 if (fp->f_vnode == NULL) {
2059 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2064 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2067 return (_fgetvp(td, fd, vpp, 0));
2071 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2074 return (_fgetvp(td, fd, vpp, FREAD));
2079 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2082 return (_fgetvp(td, fd, vpp, FWRITE));
2087 * Like fget() but loads the underlying socket, or returns an error if the
2088 * descriptor does not represent a socket.
2090 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2093 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2094 * on their file descriptor reference to prevent the socket from being free'd
2098 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2108 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2110 if (fp->f_type != DTYPE_SOCKET) {
2115 *fflagp = fp->f_flag;
2120 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2125 * Drop the reference count on the socket and XXX release the SX lock in the
2126 * future. The last reference closes the socket.
2128 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2131 fputsock(struct socket *so)
2141 fdrop(struct file *fp, struct thread *td)
2145 return (fdrop_locked(fp, td));
2149 * Drop reference on struct file passed in, may call closef if the
2150 * reference hits zero.
2151 * Expects struct file locked, and will unlock it.
2154 fdrop_locked(struct file *fp, struct thread *td)
2158 FILE_LOCK_ASSERT(fp, MA_OWNED);
2160 if (--fp->f_count > 0) {
2166 * We might have just dropped the last reference to a file
2167 * object that is for a UNIX domain socket whose message
2168 * buffers are being examined in unp_gc(). If that is the
2169 * case, FWAIT will be set in f_gcflag and we need to wait for
2170 * unp_gc() to finish its scan.
2172 while (fp->f_gcflag & FWAIT)
2173 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2175 /* We have the last ref so we can proceed without the file lock. */
2177 if (fp->f_count < 0)
2178 panic("fdrop: count < 0");
2179 if (fp->f_ops != &badfileops)
2180 error = fo_close(fp, td);
2184 sx_xlock(&filelist_lock);
2185 LIST_REMOVE(fp, f_list);
2187 sx_xunlock(&filelist_lock);
2189 uma_zfree(file_zone, fp);
2195 * Apply an advisory lock on a file descriptor.
2197 * Just attempt to get a record lock of the requested type on the entire file
2198 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2200 #ifndef _SYS_SYSPROTO_H_
2208 flock(struct thread *td, struct flock_args *uap)
2215 if ((error = fget(td, uap->fd, &fp)) != 0)
2217 if (fp->f_type != DTYPE_VNODE) {
2219 return (EOPNOTSUPP);
2224 lf.l_whence = SEEK_SET;
2227 if (uap->how & LOCK_UN) {
2228 lf.l_type = F_UNLCK;
2230 fp->f_flag &= ~FHASLOCK;
2232 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2235 if (uap->how & LOCK_EX)
2236 lf.l_type = F_WRLCK;
2237 else if (uap->how & LOCK_SH)
2238 lf.l_type = F_RDLCK;
2244 fp->f_flag |= FHASLOCK;
2246 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2247 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2254 * Duplicate the specified descriptor to a free descriptor.
2257 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2263 * If the to-be-dup'd fd number is greater than the allowed number
2264 * of file descriptors, or the fd to be dup'd has already been
2265 * closed, then reject.
2267 FILEDESC_XLOCK(fdp);
2268 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2269 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2270 FILEDESC_XUNLOCK(fdp);
2275 * There are two cases of interest here.
2277 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2279 * For ENXIO steal away the file structure from (dfd) and store it in
2280 * (indx). (dfd) is effectively closed by this operation.
2282 * Any other error code is just returned.
2287 * Check that the mode the file is being opened for is a
2288 * subset of the mode of the existing descriptor.
2291 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2293 FILEDESC_XUNLOCK(fdp);
2296 fp = fdp->fd_ofiles[indx];
2297 fdp->fd_ofiles[indx] = wfp;
2298 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2303 FILEDESC_XUNLOCK(fdp);
2306 * We now own the reference to fp that the ofiles[]
2307 * array used to own. Release it.
2314 * Steal away the file pointer from dfd and stuff it into indx.
2316 fp = fdp->fd_ofiles[indx];
2317 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2318 fdp->fd_ofiles[dfd] = NULL;
2319 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2320 fdp->fd_ofileflags[dfd] = 0;
2324 FILEDESC_XUNLOCK(fdp);
2327 * We now own the reference to fp that the ofiles[] array
2328 * used to own. Release it.
2335 FILEDESC_XUNLOCK(fdp);
2342 * Scan all active processes to see if any of them have a current or root
2343 * directory of `olddp'. If so, replace them with the new mount point.
2346 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2348 struct filedesc *fdp;
2352 if (vrefcnt(olddp) == 1)
2354 sx_slock(&allproc_lock);
2355 FOREACH_PROC_IN_SYSTEM(p) {
2360 FILEDESC_XLOCK(fdp);
2361 if (fdp->fd_cdir == olddp) {
2363 fdp->fd_cdir = newdp;
2366 if (fdp->fd_rdir == olddp) {
2368 fdp->fd_rdir = newdp;
2371 FILEDESC_XUNLOCK(fdp);
2376 sx_sunlock(&allproc_lock);
2377 if (rootvnode == olddp) {
2384 struct filedesc_to_leader *
2385 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2387 struct filedesc_to_leader *fdtol;
2389 MALLOC(fdtol, struct filedesc_to_leader *,
2390 sizeof(struct filedesc_to_leader),
2391 M_FILEDESC_TO_LEADER,
2393 fdtol->fdl_refcount = 1;
2394 fdtol->fdl_holdcount = 0;
2395 fdtol->fdl_wakeup = 0;
2396 fdtol->fdl_leader = leader;
2398 FILEDESC_XLOCK(fdp);
2399 fdtol->fdl_next = old->fdl_next;
2400 fdtol->fdl_prev = old;
2401 old->fdl_next = fdtol;
2402 fdtol->fdl_next->fdl_prev = fdtol;
2403 FILEDESC_XUNLOCK(fdp);
2405 fdtol->fdl_next = fdtol;
2406 fdtol->fdl_prev = fdtol;
2412 * Get file structures.
2415 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2418 struct filedesc *fdp;
2424 * Note: because the number of file descriptors is calculated
2425 * in different ways for sizing vs returning the data,
2426 * there is information leakage from the first loop. However,
2427 * it is of a similar order of magnitude to the leakage from
2428 * global system statistics such as kern.openfiles.
2430 error = sysctl_wire_old_buffer(req, 0);
2433 if (req->oldptr == NULL) {
2434 n = 16; /* A slight overestimate. */
2435 sx_slock(&filelist_lock);
2436 LIST_FOREACH(fp, &filehead, f_list) {
2438 * We should grab the lock, but this is an
2439 * estimate, so does it really matter?
2441 /* mtx_lock(fp->f_mtxp); */
2443 /* mtx_unlock(f->f_mtxp); */
2445 sx_sunlock(&filelist_lock);
2446 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2449 bzero(&xf, sizeof(xf));
2450 xf.xf_size = sizeof(xf);
2451 sx_slock(&allproc_lock);
2452 FOREACH_PROC_IN_SYSTEM(p) {
2453 if (p->p_state == PRS_NEW)
2456 if (p_cansee(req->td, p) != 0) {
2460 xf.xf_pid = p->p_pid;
2461 xf.xf_uid = p->p_ucred->cr_uid;
2466 FILEDESC_SLOCK(fdp);
2467 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2468 if ((fp = fdp->fd_ofiles[n]) == NULL)
2472 xf.xf_data = fp->f_data;
2473 xf.xf_vnode = fp->f_vnode;
2474 xf.xf_type = fp->f_type;
2475 xf.xf_count = fp->f_count;
2476 xf.xf_msgcount = fp->f_msgcount;
2477 xf.xf_offset = fp->f_offset;
2478 xf.xf_flag = fp->f_flag;
2479 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2483 FILEDESC_SUNLOCK(fdp);
2488 sx_sunlock(&allproc_lock);
2492 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2493 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2497 * For the purposes of debugging, generate a human-readable string for the
2501 file_type_to_name(short type)
2527 * For the purposes of debugging, identify a process (if any, perhaps one of
2528 * many) that references the passed file in its file descriptor array. Return
2531 static struct proc *
2532 file_to_first_proc(struct file *fp)
2534 struct filedesc *fdp;
2538 FOREACH_PROC_IN_SYSTEM(p) {
2539 if (p->p_state == PRS_NEW)
2544 for (n = 0; n < fdp->fd_nfiles; n++) {
2545 if (fp == fdp->fd_ofiles[n])
2553 db_print_file(struct file *fp, int header)
2558 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
2559 "File", "Type", "Data", "Flag", "GCFl", "Count",
2560 "MCount", "Vnode", "FPID", "FCmd");
2561 p = file_to_first_proc(fp);
2562 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2563 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2564 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2565 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2568 DB_SHOW_COMMAND(file, db_show_file)
2573 db_printf("usage: show file <addr>\n");
2576 fp = (struct file *)addr;
2577 db_print_file(fp, 1);
2580 DB_SHOW_COMMAND(files, db_show_files)
2586 LIST_FOREACH(fp, &filehead, f_list) {
2587 db_print_file(fp, header);
2593 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2594 &maxfilesperproc, 0, "Maximum files allowed open per process");
2596 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2597 &maxfiles, 0, "Maximum number of files");
2599 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2600 &openfiles, 0, "System-wide number of open files");
2604 filelistinit(void *dummy)
2607 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2608 NULL, NULL, UMA_ALIGN_PTR, 0);
2609 sx_init(&filelist_lock, "filelist lock");
2610 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2611 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2613 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2615 /*-------------------------------------------------------------------*/
2618 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2625 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2632 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2639 badfo_kqfilter(struct file *fp, struct knote *kn)
2646 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2653 badfo_close(struct file *fp, struct thread *td)
2659 struct fileops badfileops = {
2660 .fo_read = badfo_readwrite,
2661 .fo_write = badfo_readwrite,
2662 .fo_ioctl = badfo_ioctl,
2663 .fo_poll = badfo_poll,
2664 .fo_kqfilter = badfo_kqfilter,
2665 .fo_stat = badfo_stat,
2666 .fo_close = badfo_close,
2670 /*-------------------------------------------------------------------*/
2673 * File Descriptor pseudo-device driver (/dev/fd/).
2675 * Opening minor device N dup()s the file (if any) connected to file
2676 * descriptor N belonging to the calling process. Note that this driver
2677 * consists of only the ``open()'' routine, because all subsequent
2678 * references to this file will be direct to the other driver.
2680 * XXX: we could give this one a cloning event handler if necessary.
2685 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2689 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2690 * the file descriptor being sought for duplication. The error
2691 * return ensures that the vnode for this device will be released
2692 * by vn_open. Open will detect this special error and take the
2693 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2694 * will simply report the error.
2696 td->td_dupfd = dev2unit(dev);
2700 static struct cdevsw fildesc_cdevsw = {
2701 .d_version = D_VERSION,
2702 .d_flags = D_NEEDGIANT,
2708 fildesc_drvinit(void *unused)
2712 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2713 make_dev_alias(dev, "stdin");
2714 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2715 make_dev_alias(dev, "stdout");
2716 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2717 make_dev_alias(dev, "stderr");
2720 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)