2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_compat.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
47 #include <sys/fcntl.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mqueue.h>
58 #include <sys/mutex.h>
59 #include <sys/namei.h>
62 #include <sys/resourcevar.h>
63 #include <sys/signalvar.h>
64 #include <sys/socketvar.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
70 #include <sys/unistd.h>
71 #include <sys/vnode.h>
73 #include <security/audit/audit.h>
79 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
80 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
81 "file desc to leader structures");
82 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
84 static uma_zone_t file_zone;
87 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
88 enum dup_type { DUP_VARIABLE, DUP_FIXED };
90 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
92 static int fd_first_free(struct filedesc *, int, int);
93 static int fd_last_used(struct filedesc *, int, int);
94 static void fdgrowtable(struct filedesc *, int);
95 static int fdrop_locked(struct file *fp, struct thread *td);
96 static void fdunused(struct filedesc *fdp, int fd);
97 static void fdused(struct filedesc *fdp, int fd);
100 * A process is initially started out with NDFILE descriptors stored within
101 * this structure, selected to be enough for typical applications based on
102 * the historical limit of 20 open files (and the usage of descriptors by
103 * shells). If these descriptors are exhausted, a larger descriptor table
104 * may be allocated, up to a process' resource limit; the internal arrays
108 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
109 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
110 #define NDSLOT(x) ((x) / NDENTRIES)
111 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
112 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
115 * Storage required per open file descriptor.
117 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
120 * Basic allocation of descriptors:
121 * one of the above, plus arrays for NDFILE descriptors.
124 struct filedesc fd_fd;
126 * These arrays are used when the number of open files is
127 * <= NDFILE, and are then pointed to by the pointers above.
129 struct file *fd_dfiles[NDFILE];
130 char fd_dfileflags[NDFILE];
131 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
135 * Descriptor management.
137 struct filelist filehead; /* head of list of open files */
138 int openfiles; /* actual number of open files */
139 struct sx filelist_lock; /* sx to protect filelist */
140 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
141 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
143 /* A mutex to protect the association between a proc and filedesc. */
144 static struct mtx fdesc_mtx;
147 * Find the first zero bit in the given bitmap, starting at low and not
148 * exceeding size - 1.
151 fd_first_free(struct filedesc *fdp, int low, int size)
153 NDSLOTTYPE *map = fdp->fd_map;
161 if (low % NDENTRIES) {
162 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
163 if ((mask &= ~map[off]) != 0UL)
164 return (off * NDENTRIES + ffsl(mask) - 1);
167 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
168 if (map[off] != ~0UL)
169 return (off * NDENTRIES + ffsl(~map[off]) - 1);
174 * Find the highest non-zero bit in the given bitmap, starting at low and
175 * not exceeding size - 1.
178 fd_last_used(struct filedesc *fdp, int low, int size)
180 NDSLOTTYPE *map = fdp->fd_map;
188 if (size % NDENTRIES) {
189 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
190 if ((mask &= map[off]) != 0)
191 return (off * NDENTRIES + flsl(mask) - 1);
194 for (minoff = NDSLOT(low); off >= minoff; --off)
196 return (off * NDENTRIES + flsl(map[off]) - 1);
201 fdisused(struct filedesc *fdp, int fd)
203 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
204 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
205 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
209 * Mark a file descriptor as used.
212 fdused(struct filedesc *fdp, int fd)
214 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
215 KASSERT(!fdisused(fdp, fd),
216 ("fd already used"));
217 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
218 if (fd > fdp->fd_lastfile)
219 fdp->fd_lastfile = fd;
220 if (fd == fdp->fd_freefile)
221 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
225 * Mark a file descriptor as unused.
228 fdunused(struct filedesc *fdp, int fd)
230 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
231 KASSERT(fdisused(fdp, fd),
232 ("fd is already unused"));
233 KASSERT(fdp->fd_ofiles[fd] == NULL,
234 ("fd is still in use"));
235 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
236 if (fd < fdp->fd_freefile)
237 fdp->fd_freefile = fd;
238 if (fd == fdp->fd_lastfile)
239 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
243 * System calls on descriptors.
245 #ifndef _SYS_SYSPROTO_H_
246 struct getdtablesize_args {
252 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
254 struct proc *p = td->td_proc;
258 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
264 * Duplicate a file descriptor to a particular value.
266 * Note: keep in mind that a potential race condition exists when closing
267 * descriptors from a shared descriptor table (via rfork).
269 #ifndef _SYS_SYSPROTO_H_
277 dup2(struct thread *td, struct dup2_args *uap)
280 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
285 * Duplicate a file descriptor.
287 #ifndef _SYS_SYSPROTO_H_
294 dup(struct thread *td, struct dup_args *uap)
297 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
301 * The file control system call.
303 #ifndef _SYS_SYSPROTO_H_
312 fcntl(struct thread *td, struct fcntl_args *uap)
323 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
332 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
335 if (uap->cmd == F_GETLK)
336 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
341 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
343 struct filedesc *fdp;
354 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
355 * avoid grabbing Giant for calls we know don't need it.
375 if ((unsigned)fd >= fdp->fd_nfiles ||
376 (fp = fdp->fd_ofiles[fd]) == NULL) {
377 FILEDESC_UNLOCK(fdp);
381 pop = &fdp->fd_ofileflags[fd];
385 /* mtx_assert(&Giant, MA_NOTOWNED); */
386 FILEDESC_UNLOCK(fdp);
389 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
390 newmin >= maxfilesperproc) {
396 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
400 /* mtx_assert(&Giant, MA_NOTOWNED); */
401 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
402 FILEDESC_UNLOCK(fdp);
406 /* mtx_assert(&Giant, MA_NOTOWNED); */
407 *pop = (*pop &~ UF_EXCLOSE) |
408 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
409 FILEDESC_UNLOCK(fdp);
413 /* mtx_assert(&Giant, MA_NOTOWNED); */
415 td->td_retval[0] = OFLAGS(fp->f_flag);
417 FILEDESC_UNLOCK(fdp);
421 mtx_assert(&Giant, MA_OWNED);
424 fp->f_flag &= ~FCNTLFLAGS;
425 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
427 FILEDESC_UNLOCK(fdp);
428 tmp = fp->f_flag & FNONBLOCK;
429 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
434 tmp = fp->f_flag & FASYNC;
435 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
441 fp->f_flag &= ~FNONBLOCK;
444 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
449 mtx_assert(&Giant, MA_OWNED);
451 FILEDESC_UNLOCK(fdp);
452 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
454 td->td_retval[0] = tmp;
459 mtx_assert(&Giant, MA_OWNED);
461 FILEDESC_UNLOCK(fdp);
463 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
468 mtx_assert(&Giant, MA_OWNED);
470 /* FALLTHROUGH F_SETLK */
473 mtx_assert(&Giant, MA_OWNED);
474 if (fp->f_type != DTYPE_VNODE) {
475 FILEDESC_UNLOCK(fdp);
480 flp = (struct flock *)arg;
481 if (flp->l_whence == SEEK_CUR) {
482 if (fp->f_offset < 0 ||
484 fp->f_offset > OFF_MAX - flp->l_start)) {
485 FILEDESC_UNLOCK(fdp);
489 flp->l_start += fp->f_offset;
493 * VOP_ADVLOCK() may block.
496 FILEDESC_UNLOCK(fdp);
499 switch (flp->l_type) {
501 if ((fp->f_flag & FREAD) == 0) {
505 PROC_LOCK(p->p_leader);
506 p->p_leader->p_flag |= P_ADVLOCK;
507 PROC_UNLOCK(p->p_leader);
508 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
512 if ((fp->f_flag & FWRITE) == 0) {
516 PROC_LOCK(p->p_leader);
517 p->p_leader->p_flag |= P_ADVLOCK;
518 PROC_UNLOCK(p->p_leader);
519 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
523 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
530 /* Check for race with close */
531 FILEDESC_LOCK_FAST(fdp);
532 if ((unsigned) fd >= fdp->fd_nfiles ||
533 fp != fdp->fd_ofiles[fd]) {
534 FILEDESC_UNLOCK_FAST(fdp);
535 flp->l_whence = SEEK_SET;
538 flp->l_type = F_UNLCK;
539 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
540 F_UNLCK, flp, F_POSIX);
542 FILEDESC_UNLOCK_FAST(fdp);
547 mtx_assert(&Giant, MA_OWNED);
548 if (fp->f_type != DTYPE_VNODE) {
549 FILEDESC_UNLOCK(fdp);
553 flp = (struct flock *)arg;
554 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
555 flp->l_type != F_UNLCK) {
556 FILEDESC_UNLOCK(fdp);
560 if (flp->l_whence == SEEK_CUR) {
561 if ((flp->l_start > 0 &&
562 fp->f_offset > OFF_MAX - flp->l_start) ||
564 fp->f_offset < OFF_MIN - flp->l_start)) {
565 FILEDESC_UNLOCK(fdp);
569 flp->l_start += fp->f_offset;
572 * VOP_ADVLOCK() may block.
575 FILEDESC_UNLOCK(fdp);
577 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
582 FILEDESC_UNLOCK(fdp);
593 * Common code for dup, dup2, and fcntl(F_DUPFD).
596 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
598 struct filedesc *fdp;
602 int error, holdleaders, maxfd;
604 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
605 ("invalid dup type %d", type));
611 * Verify we have a valid descriptor to dup from and possibly to
614 if (old < 0 || new < 0)
617 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
623 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
624 FILEDESC_UNLOCK(fdp);
627 if (type == DUP_FIXED && old == new) {
629 FILEDESC_UNLOCK(fdp);
632 fp = fdp->fd_ofiles[old];
636 * If the caller specified a file descriptor, make sure the file
637 * table is large enough to hold it, and grab it. Otherwise, just
638 * allocate a new descriptor the usual way. Since the filedesc
639 * lock may be temporarily dropped in the process, we have to look
642 if (type == DUP_FIXED) {
643 if (new >= fdp->fd_nfiles)
644 fdgrowtable(fdp, new + 1);
645 if (fdp->fd_ofiles[new] == NULL)
648 if ((error = fdalloc(td, new, &new)) != 0) {
649 FILEDESC_UNLOCK(fdp);
656 * If the old file changed out from under us then treat it as a
657 * bad file descriptor. Userland should do its own locking to
660 if (fdp->fd_ofiles[old] != fp) {
661 /* we've allocated a descriptor which we won't use */
662 if (fdp->fd_ofiles[new] == NULL)
664 FILEDESC_UNLOCK(fdp);
669 ("new fd is same as old"));
672 * Save info on the descriptor being overwritten. We cannot close
673 * it without introducing an ownership race for the slot, since we
674 * need to drop the filedesc lock to call closef().
676 * XXX this duplicates parts of close().
678 delfp = fdp->fd_ofiles[new];
681 if (td->td_proc->p_fdtol != NULL) {
683 * Ask fdfree() to sleep to ensure that all relevant
684 * process leaders can be traversed in closef().
686 fdp->fd_holdleaderscount++;
692 * Duplicate the source descriptor
694 fdp->fd_ofiles[new] = fp;
695 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
696 if (new > fdp->fd_lastfile)
697 fdp->fd_lastfile = new;
701 * If we dup'd over a valid file, we now own the reference to it
702 * and must dispose of it using closef() semantics (as if a
703 * close() were performed on it).
705 * XXX this duplicates parts of close().
708 knote_fdclose(td, new);
709 if (delfp->f_type == DTYPE_MQUEUE)
710 mq_fdclose(td, new, delfp);
711 FILEDESC_UNLOCK(fdp);
712 (void) closef(delfp, td);
714 FILEDESC_LOCK_FAST(fdp);
715 fdp->fd_holdleaderscount--;
716 if (fdp->fd_holdleaderscount == 0 &&
717 fdp->fd_holdleaderswakeup != 0) {
718 fdp->fd_holdleaderswakeup = 0;
719 wakeup(&fdp->fd_holdleaderscount);
721 FILEDESC_UNLOCK_FAST(fdp);
724 FILEDESC_UNLOCK(fdp);
730 * If sigio is on the list associated with a process or process group,
731 * disable signalling from the device, remove sigio from the list and
735 funsetown(struct sigio **sigiop)
745 *(sigio->sio_myref) = NULL;
746 if ((sigio)->sio_pgid < 0) {
747 struct pgrp *pg = (sigio)->sio_pgrp;
749 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
753 struct proc *p = (sigio)->sio_proc;
755 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
760 crfree(sigio->sio_ucred);
761 FREE(sigio, M_SIGIO);
765 * Free a list of sigio structures.
766 * We only need to lock the SIGIO_LOCK because we have made ourselves
767 * inaccessible to callers of fsetown and therefore do not need to lock
768 * the proc or pgrp struct for the list manipulation.
771 funsetownlst(struct sigiolst *sigiolst)
777 sigio = SLIST_FIRST(sigiolst);
784 * Every entry of the list should belong
785 * to a single proc or pgrp.
787 if (sigio->sio_pgid < 0) {
788 pg = sigio->sio_pgrp;
789 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
790 } else /* if (sigio->sio_pgid > 0) */ {
792 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
796 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
797 *(sigio->sio_myref) = NULL;
799 KASSERT(sigio->sio_pgid < 0,
800 ("Proc sigio in pgrp sigio list"));
801 KASSERT(sigio->sio_pgrp == pg,
802 ("Bogus pgrp in sigio list"));
804 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
807 } else /* if (p != NULL) */ {
808 KASSERT(sigio->sio_pgid > 0,
809 ("Pgrp sigio in proc sigio list"));
810 KASSERT(sigio->sio_proc == p,
811 ("Bogus proc in sigio list"));
813 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
818 crfree(sigio->sio_ucred);
819 FREE(sigio, M_SIGIO);
826 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
828 * After permission checking, add a sigio structure to the sigio list for
829 * the process or process group.
832 fsetown(pid_t pgid, struct sigio **sigiop)
846 /* Allocate and fill in the new sigio out of locks. */
847 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
848 sigio->sio_pgid = pgid;
849 sigio->sio_ucred = crhold(curthread->td_ucred);
850 sigio->sio_myref = sigiop;
852 sx_slock(&proctree_lock);
861 * Policy - Don't allow a process to FSETOWN a process
862 * in another session.
864 * Remove this test to allow maximum flexibility or
865 * restrict FSETOWN to the current process or process
866 * group for maximum safety.
869 if (proc->p_session != curthread->td_proc->p_session) {
875 } else /* if (pgid < 0) */ {
876 pgrp = pgfind(-pgid);
884 * Policy - Don't allow a process to FSETOWN a process
885 * in another session.
887 * Remove this test to allow maximum flexibility or
888 * restrict FSETOWN to the current process or process
889 * group for maximum safety.
891 if (pgrp->pg_session != curthread->td_proc->p_session) {
902 * Since funsetownlst() is called without the proctree
903 * locked, we need to check for P_WEXIT.
904 * XXX: is ESRCH correct?
906 if ((proc->p_flag & P_WEXIT) != 0) {
911 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
912 sigio->sio_proc = proc;
916 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
917 sigio->sio_pgrp = pgrp;
920 sx_sunlock(&proctree_lock);
927 sx_sunlock(&proctree_lock);
928 crfree(sigio->sio_ucred);
929 FREE(sigio, M_SIGIO);
934 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
938 struct sigio **sigiop;
943 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
949 * Close a file descriptor.
951 #ifndef _SYS_SYSPROTO_H_
960 struct close_args *uap;
963 return (kern_close(td, uap->fd));
971 struct filedesc *fdp;
978 fdp = td->td_proc->p_fd;
980 AUDIT_SYSCLOSE(td, fd);
983 if ((unsigned)fd >= fdp->fd_nfiles ||
984 (fp = fdp->fd_ofiles[fd]) == NULL) {
985 FILEDESC_UNLOCK(fdp);
988 fdp->fd_ofiles[fd] = NULL;
989 fdp->fd_ofileflags[fd] = 0;
991 if (td->td_proc->p_fdtol != NULL) {
993 * Ask fdfree() to sleep to ensure that all relevant
994 * process leaders can be traversed in closef().
996 fdp->fd_holdleaderscount++;
1001 * We now hold the fp reference that used to be owned by the descriptor
1003 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1004 * race of the fd getting opened, a knote added, and deleteing a knote
1007 knote_fdclose(td, fd);
1008 if (fp->f_type == DTYPE_MQUEUE)
1009 mq_fdclose(td, fd, fp);
1010 FILEDESC_UNLOCK(fdp);
1012 error = closef(fp, td);
1014 FILEDESC_LOCK_FAST(fdp);
1015 fdp->fd_holdleaderscount--;
1016 if (fdp->fd_holdleaderscount == 0 &&
1017 fdp->fd_holdleaderswakeup != 0) {
1018 fdp->fd_holdleaderswakeup = 0;
1019 wakeup(&fdp->fd_holdleaderscount);
1021 FILEDESC_UNLOCK_FAST(fdp);
1026 #if defined(COMPAT_43)
1028 * Return status information about a file descriptor.
1030 #ifndef _SYS_SYSPROTO_H_
1031 struct ofstat_args {
1038 ofstat(struct thread *td, struct ofstat_args *uap)
1044 error = kern_fstat(td, uap->fd, &ub);
1047 error = copyout(&oub, uap->sb, sizeof(oub));
1051 #endif /* COMPAT_43 */
1054 * Return status information about a file descriptor.
1056 #ifndef _SYS_SYSPROTO_H_
1064 fstat(struct thread *td, struct fstat_args *uap)
1069 error = kern_fstat(td, uap->fd, &ub);
1071 error = copyout(&ub, uap->sb, sizeof(ub));
1076 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1083 if ((error = fget(td, fd, &fp)) != 0)
1086 AUDIT_ARG(file, td->td_proc, fp);
1088 error = fo_stat(fp, sbp, td->td_ucred, td);
1094 * Return status information about a file descriptor.
1096 #ifndef _SYS_SYSPROTO_H_
1097 struct nfstat_args {
1104 nfstat(struct thread *td, struct nfstat_args *uap)
1110 error = kern_fstat(td, uap->fd, &ub);
1112 cvtnstat(&ub, &nub);
1113 error = copyout(&nub, uap->sb, sizeof(nub));
1119 * Return pathconf information about a file descriptor.
1121 #ifndef _SYS_SYSPROTO_H_
1122 struct fpathconf_args {
1129 fpathconf(struct thread *td, struct fpathconf_args *uap)
1135 if ((error = fget(td, uap->fd, &fp)) != 0)
1138 /* If asynchronous I/O is available, it works for all descriptors. */
1139 if (uap->name == _PC_ASYNC_IO) {
1140 td->td_retval[0] = async_io_version;
1146 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1147 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1148 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1149 VOP_UNLOCK(vp, 0, td);
1150 VFS_UNLOCK_GIANT(vfslocked);
1151 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1152 if (uap->name != _PC_PIPE_BUF) {
1155 td->td_retval[0] = PIPE_BUF;
1167 * Grow the file table to accomodate (at least) nfd descriptors. This may
1168 * block and drop the filedesc lock, but it will reacquire it before
1172 fdgrowtable(struct filedesc *fdp, int nfd)
1174 struct file **ntable;
1176 int nnfiles, onfiles;
1179 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1181 KASSERT(fdp->fd_nfiles > 0,
1182 ("zero-length file table"));
1184 /* compute the size of the new table */
1185 onfiles = fdp->fd_nfiles;
1186 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1187 if (nnfiles <= onfiles)
1188 /* the table is already large enough */
1191 /* allocate a new table and (if required) new bitmaps */
1192 FILEDESC_UNLOCK(fdp);
1193 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1194 M_FILEDESC, M_ZERO | M_WAITOK);
1195 nfileflags = (char *)&ntable[nnfiles];
1196 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1197 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1198 M_FILEDESC, M_ZERO | M_WAITOK);
1204 * We now have new tables ready to go. Since we dropped the
1205 * filedesc lock to call malloc(), watch out for a race.
1207 onfiles = fdp->fd_nfiles;
1208 if (onfiles >= nnfiles) {
1209 /* we lost the race, but that's OK */
1210 free(ntable, M_FILEDESC);
1212 free(nmap, M_FILEDESC);
1215 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1216 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1217 if (onfiles > NDFILE)
1218 free(fdp->fd_ofiles, M_FILEDESC);
1219 fdp->fd_ofiles = ntable;
1220 fdp->fd_ofileflags = nfileflags;
1221 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1222 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1223 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1224 free(fdp->fd_map, M_FILEDESC);
1227 fdp->fd_nfiles = nnfiles;
1231 * Allocate a file descriptor for the process.
1234 fdalloc(struct thread *td, int minfd, int *result)
1236 struct proc *p = td->td_proc;
1237 struct filedesc *fdp = p->p_fd;
1240 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1242 if (fdp->fd_freefile > minfd)
1243 minfd = fdp->fd_freefile;
1246 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1250 * Search the bitmap for a free descriptor. If none is found, try
1251 * to grow the file table. Keep at it until we either get a file
1252 * descriptor or run into process or system limits; fdgrowtable()
1253 * may drop the filedesc lock, so we're in a race.
1256 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1259 if (fd < fdp->fd_nfiles)
1261 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1265 * Perform some sanity checks, then mark the file descriptor as
1266 * used and return it to the caller.
1268 KASSERT(!fdisused(fdp, fd),
1269 ("fd_first_free() returned non-free descriptor"));
1270 KASSERT(fdp->fd_ofiles[fd] == NULL,
1271 ("free descriptor isn't"));
1272 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1279 * Check to see whether n user file descriptors
1280 * are available to the process p.
1283 fdavail(struct thread *td, int n)
1285 struct proc *p = td->td_proc;
1286 struct filedesc *fdp = td->td_proc->p_fd;
1290 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
1293 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1295 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1297 last = min(fdp->fd_nfiles, lim);
1298 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1299 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1300 if (*fpp == NULL && --n <= 0)
1307 * Create a new open file structure and allocate
1308 * a file decriptor for the process that refers to it.
1309 * We add one reference to the file for the descriptor table
1310 * and one reference for resultfp. This is to prevent us being
1311 * preempted and the entry in the descriptor table closed after
1312 * we release the FILEDESC lock.
1315 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1317 struct proc *p = td->td_proc;
1318 struct file *fp, *fq;
1320 int maxuserfiles = maxfiles - (maxfiles / 20);
1321 static struct timeval lastfail;
1324 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1325 sx_xlock(&filelist_lock);
1327 if ((openfiles >= maxuserfiles &&
1328 priv_check_cred(td->td_ucred, PRIV_MAXFILES, SUSER_RUID) != 0) ||
1329 openfiles >= maxfiles) {
1330 if (ppsratecheck(&lastfail, &curfail, 1)) {
1331 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1332 td->td_ucred->cr_ruid);
1334 sx_xunlock(&filelist_lock);
1335 uma_zfree(file_zone, fp);
1341 * If the process has file descriptor zero open, add the new file
1342 * descriptor to the list of open files at that point, otherwise
1343 * put it at the front of the list of open files.
1345 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1349 fp->f_cred = crhold(td->td_ucred);
1350 fp->f_ops = &badfileops;
1353 FILEDESC_LOCK(p->p_fd);
1354 if ((fq = p->p_fd->fd_ofiles[0])) {
1355 LIST_INSERT_AFTER(fq, fp, f_list);
1357 LIST_INSERT_HEAD(&filehead, fp, f_list);
1359 sx_xunlock(&filelist_lock);
1360 if ((error = fdalloc(td, 0, &i))) {
1361 FILEDESC_UNLOCK(p->p_fd);
1367 p->p_fd->fd_ofiles[i] = fp;
1368 FILEDESC_UNLOCK(p->p_fd);
1377 * Build a new filedesc structure from another.
1378 * Copy the current, root, and jail root vnode references.
1381 fdinit(struct filedesc *fdp)
1383 struct filedesc0 *newfdp;
1385 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1386 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1389 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1390 if (newfdp->fd_fd.fd_cdir)
1391 VREF(newfdp->fd_fd.fd_cdir);
1392 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1393 if (newfdp->fd_fd.fd_rdir)
1394 VREF(newfdp->fd_fd.fd_rdir);
1395 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1396 if (newfdp->fd_fd.fd_jdir)
1397 VREF(newfdp->fd_fd.fd_jdir);
1398 FILEDESC_UNLOCK(fdp);
1401 /* Create the file descriptor table. */
1402 newfdp->fd_fd.fd_refcnt = 1;
1403 newfdp->fd_fd.fd_holdcnt = 1;
1404 newfdp->fd_fd.fd_cmask = CMASK;
1405 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1406 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1407 newfdp->fd_fd.fd_nfiles = NDFILE;
1408 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1409 newfdp->fd_fd.fd_lastfile = -1;
1410 return (&newfdp->fd_fd);
1413 static struct filedesc *
1414 fdhold(struct proc *p)
1416 struct filedesc *fdp;
1418 mtx_lock(&fdesc_mtx);
1422 mtx_unlock(&fdesc_mtx);
1427 fddrop(struct filedesc *fdp)
1431 mtx_lock(&fdesc_mtx);
1432 i = --fdp->fd_holdcnt;
1433 mtx_unlock(&fdesc_mtx);
1437 mtx_destroy(&fdp->fd_mtx);
1438 FREE(fdp, M_FILEDESC);
1442 * Share a filedesc structure.
1445 fdshare(struct filedesc *fdp)
1447 FILEDESC_LOCK_FAST(fdp);
1449 FILEDESC_UNLOCK_FAST(fdp);
1454 * Unshare a filedesc structure, if necessary by making a copy
1457 fdunshare(struct proc *p, struct thread *td)
1460 FILEDESC_LOCK_FAST(p->p_fd);
1461 if (p->p_fd->fd_refcnt > 1) {
1462 struct filedesc *tmp;
1464 FILEDESC_UNLOCK_FAST(p->p_fd);
1465 tmp = fdcopy(p->p_fd);
1469 FILEDESC_UNLOCK_FAST(p->p_fd);
1473 * Copy a filedesc structure.
1474 * A NULL pointer in returns a NULL reference, this is to ease callers,
1478 fdcopy(struct filedesc *fdp)
1480 struct filedesc *newfdp;
1483 /* Certain daemons might not have file descriptors. */
1487 newfdp = fdinit(fdp);
1488 FILEDESC_LOCK_FAST(fdp);
1489 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1490 FILEDESC_UNLOCK_FAST(fdp);
1491 FILEDESC_LOCK(newfdp);
1492 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1493 FILEDESC_UNLOCK(newfdp);
1494 FILEDESC_LOCK_FAST(fdp);
1496 /* copy everything except kqueue descriptors */
1497 newfdp->fd_freefile = -1;
1498 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1499 if (fdisused(fdp, i) &&
1500 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1501 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1502 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1503 fhold(newfdp->fd_ofiles[i]);
1504 newfdp->fd_lastfile = i;
1506 if (newfdp->fd_freefile == -1)
1507 newfdp->fd_freefile = i;
1510 FILEDESC_UNLOCK_FAST(fdp);
1511 FILEDESC_LOCK(newfdp);
1512 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1513 if (newfdp->fd_ofiles[i] != NULL)
1515 FILEDESC_UNLOCK(newfdp);
1516 FILEDESC_LOCK_FAST(fdp);
1517 if (newfdp->fd_freefile == -1)
1518 newfdp->fd_freefile = i;
1519 newfdp->fd_cmask = fdp->fd_cmask;
1520 FILEDESC_UNLOCK_FAST(fdp);
1525 * Release a filedesc structure.
1528 fdfree(struct thread *td)
1530 struct filedesc *fdp;
1533 struct filedesc_to_leader *fdtol;
1535 struct vnode *cdir, *jdir, *rdir, *vp;
1538 /* Certain daemons might not have file descriptors. */
1539 fdp = td->td_proc->p_fd;
1543 /* Check for special need to clear POSIX style locks */
1544 fdtol = td->td_proc->p_fdtol;
1545 if (fdtol != NULL) {
1547 KASSERT(fdtol->fdl_refcount > 0,
1548 ("filedesc_to_refcount botch: fdl_refcount=%d",
1549 fdtol->fdl_refcount));
1550 if (fdtol->fdl_refcount == 1 &&
1551 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1552 for (i = 0, fpp = fdp->fd_ofiles;
1553 i <= fdp->fd_lastfile;
1556 (*fpp)->f_type != DTYPE_VNODE)
1560 FILEDESC_UNLOCK(fdp);
1561 lf.l_whence = SEEK_SET;
1564 lf.l_type = F_UNLCK;
1566 locked = VFS_LOCK_GIANT(vp->v_mount);
1567 (void) VOP_ADVLOCK(vp,
1568 (caddr_t)td->td_proc->
1573 VFS_UNLOCK_GIANT(locked);
1576 fpp = fdp->fd_ofiles + i;
1580 if (fdtol->fdl_refcount == 1) {
1581 if (fdp->fd_holdleaderscount > 0 &&
1582 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1584 * close() or do_dup() has cleared a reference
1585 * in a shared file descriptor table.
1587 fdp->fd_holdleaderswakeup = 1;
1588 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1589 PLOCK, "fdlhold", 0);
1592 if (fdtol->fdl_holdcount > 0) {
1594 * Ensure that fdtol->fdl_leader
1595 * remains valid in closef().
1597 fdtol->fdl_wakeup = 1;
1598 msleep(fdtol, &fdp->fd_mtx,
1599 PLOCK, "fdlhold", 0);
1603 fdtol->fdl_refcount--;
1604 if (fdtol->fdl_refcount == 0 &&
1605 fdtol->fdl_holdcount == 0) {
1606 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1607 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1610 td->td_proc->p_fdtol = NULL;
1611 FILEDESC_UNLOCK(fdp);
1613 FREE(fdtol, M_FILEDESC_TO_LEADER);
1615 FILEDESC_LOCK_FAST(fdp);
1616 i = --fdp->fd_refcnt;
1617 FILEDESC_UNLOCK_FAST(fdp);
1621 * We are the last reference to the structure, so we can
1622 * safely assume it will not change out from under us.
1624 fpp = fdp->fd_ofiles;
1625 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1627 (void) closef(*fpp, td);
1631 /* XXX This should happen earlier. */
1632 mtx_lock(&fdesc_mtx);
1633 td->td_proc->p_fd = NULL;
1634 mtx_unlock(&fdesc_mtx);
1636 if (fdp->fd_nfiles > NDFILE)
1637 FREE(fdp->fd_ofiles, M_FILEDESC);
1638 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1639 FREE(fdp->fd_map, M_FILEDESC);
1643 cdir = fdp->fd_cdir;
1644 fdp->fd_cdir = NULL;
1645 rdir = fdp->fd_rdir;
1646 fdp->fd_rdir = NULL;
1647 jdir = fdp->fd_jdir;
1648 fdp->fd_jdir = NULL;
1649 FILEDESC_UNLOCK(fdp);
1652 locked = VFS_LOCK_GIANT(cdir->v_mount);
1654 VFS_UNLOCK_GIANT(locked);
1657 locked = VFS_LOCK_GIANT(rdir->v_mount);
1659 VFS_UNLOCK_GIANT(locked);
1662 locked = VFS_LOCK_GIANT(jdir->v_mount);
1664 VFS_UNLOCK_GIANT(locked);
1671 * For setugid programs, we don't want to people to use that setugidness
1672 * to generate error messages which write to a file which otherwise would
1673 * otherwise be off-limits to the process. We check for filesystems where
1674 * the vnode can change out from under us after execve (like [lin]procfs).
1676 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1677 * sufficient. We also don't check for setugidness since we know we are.
1680 is_unsafe(struct file *fp)
1682 if (fp->f_type == DTYPE_VNODE) {
1683 struct vnode *vp = fp->f_vnode;
1685 if ((vp->v_vflag & VV_PROCDEP) != 0)
1692 * Make this setguid thing safe, if at all possible.
1695 setugidsafety(struct thread *td)
1697 struct filedesc *fdp;
1700 /* Certain daemons might not have file descriptors. */
1701 fdp = td->td_proc->p_fd;
1706 * Note: fdp->fd_ofiles may be reallocated out from under us while
1707 * we are blocked in a close. Be careful!
1710 for (i = 0; i <= fdp->fd_lastfile; i++) {
1713 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1716 knote_fdclose(td, i);
1718 * NULL-out descriptor prior to close to avoid
1719 * a race while close blocks.
1721 fp = fdp->fd_ofiles[i];
1722 fdp->fd_ofiles[i] = NULL;
1723 fdp->fd_ofileflags[i] = 0;
1725 FILEDESC_UNLOCK(fdp);
1726 (void) closef(fp, td);
1730 FILEDESC_UNLOCK(fdp);
1734 * If a specific file object occupies a specific file descriptor,
1735 * close the file descriptor entry and drop a reference on the file
1736 * object. This is a convenience function to handle a subsequent
1737 * error in a function that calls falloc() that handles the race that
1738 * another thread might have closed the file descriptor out from under
1739 * the thread creating the file object.
1742 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1746 if (fdp->fd_ofiles[idx] == fp) {
1747 fdp->fd_ofiles[idx] = NULL;
1749 FILEDESC_UNLOCK(fdp);
1752 FILEDESC_UNLOCK(fdp);
1757 * Close any files on exec?
1760 fdcloseexec(struct thread *td)
1762 struct filedesc *fdp;
1765 /* Certain daemons might not have file descriptors. */
1766 fdp = td->td_proc->p_fd;
1773 * We cannot cache fd_ofiles or fd_ofileflags since operations
1774 * may block and rip them out from under us.
1776 for (i = 0; i <= fdp->fd_lastfile; i++) {
1777 if (fdp->fd_ofiles[i] != NULL &&
1778 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1779 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1782 knote_fdclose(td, i);
1784 * NULL-out descriptor prior to close to avoid
1785 * a race while close blocks.
1787 fp = fdp->fd_ofiles[i];
1788 fdp->fd_ofiles[i] = NULL;
1789 fdp->fd_ofileflags[i] = 0;
1791 if (fp->f_type == DTYPE_MQUEUE)
1792 mq_fdclose(td, i, fp);
1793 FILEDESC_UNLOCK(fdp);
1794 (void) closef(fp, td);
1798 FILEDESC_UNLOCK(fdp);
1802 * It is unsafe for set[ug]id processes to be started with file
1803 * descriptors 0..2 closed, as these descriptors are given implicit
1804 * significance in the Standard C library. fdcheckstd() will create a
1805 * descriptor referencing /dev/null for each of stdin, stdout, and
1806 * stderr that is not already open.
1809 fdcheckstd(struct thread *td)
1811 struct nameidata nd;
1812 struct filedesc *fdp;
1815 int fd, i, error, flags, devnull;
1817 fdp = td->td_proc->p_fd;
1820 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1823 for (i = 0; i < 3; i++) {
1824 if (fdp->fd_ofiles[i] != NULL)
1828 error = falloc(td, &fp, &fd);
1831 /* Note extra ref on `fp' held for us by falloc(). */
1832 KASSERT(fd == i, ("oof, we didn't get our fd"));
1833 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1835 flags = FREAD | FWRITE;
1836 error = vn_open(&nd, &flags, 0, fd);
1839 * Someone may have closed the entry in the
1840 * file descriptor table, so check it hasn't
1841 * changed before dropping the reference count.
1844 KASSERT(fdp->fd_ofiles[fd] == fp,
1845 ("table not shared, how did it change?"));
1846 fdp->fd_ofiles[fd] = NULL;
1848 FILEDESC_UNLOCK(fdp);
1853 vfslocked = NDHASGIANT(&nd);
1854 NDFREE(&nd, NDF_ONLY_PNBUF);
1856 fp->f_vnode = nd.ni_vp;
1857 if (fp->f_data == NULL)
1858 fp->f_data = nd.ni_vp;
1859 if (fp->f_ops == &badfileops)
1861 fp->f_type = DTYPE_VNODE;
1862 VOP_UNLOCK(nd.ni_vp, 0, td);
1863 VFS_UNLOCK_GIANT(vfslocked);
1867 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1876 * Internal form of close.
1877 * Decrement reference count on file structure.
1878 * Note: td may be NULL when closing a file that was being passed in a
1881 * XXXRW: Giant is not required for the caller, but often will be held; this
1882 * makes it moderately likely the Giant will be recursed in the VFS case.
1885 closef(struct file *fp, struct thread *td)
1889 struct filedesc_to_leader *fdtol;
1890 struct filedesc *fdp;
1893 * POSIX record locking dictates that any close releases ALL
1894 * locks owned by this process. This is handled by setting
1895 * a flag in the unlock to free ONLY locks obeying POSIX
1896 * semantics, and not to free BSD-style file locks.
1897 * If the descriptor was in a message, POSIX-style locks
1898 * aren't passed with the descriptor, and the thread pointer
1899 * will be NULL. Callers should be careful only to pass a
1900 * NULL thread pointer when there really is no owning
1901 * context that might have locks, or the locks will be
1904 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1908 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1909 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1910 lf.l_whence = SEEK_SET;
1913 lf.l_type = F_UNLCK;
1914 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1915 F_UNLCK, &lf, F_POSIX);
1917 fdtol = td->td_proc->p_fdtol;
1918 if (fdtol != NULL) {
1920 * Handle special case where file descriptor table
1921 * is shared between multiple process leaders.
1923 fdp = td->td_proc->p_fd;
1925 for (fdtol = fdtol->fdl_next;
1926 fdtol != td->td_proc->p_fdtol;
1927 fdtol = fdtol->fdl_next) {
1928 if ((fdtol->fdl_leader->p_flag &
1931 fdtol->fdl_holdcount++;
1932 FILEDESC_UNLOCK(fdp);
1933 lf.l_whence = SEEK_SET;
1936 lf.l_type = F_UNLCK;
1938 (void) VOP_ADVLOCK(vp,
1939 (caddr_t)fdtol->fdl_leader,
1940 F_UNLCK, &lf, F_POSIX);
1942 fdtol->fdl_holdcount--;
1943 if (fdtol->fdl_holdcount == 0 &&
1944 fdtol->fdl_wakeup != 0) {
1945 fdtol->fdl_wakeup = 0;
1949 FILEDESC_UNLOCK(fdp);
1951 VFS_UNLOCK_GIANT(vfslocked);
1953 return (fdrop(fp, td));
1957 * Extract the file pointer associated with the specified descriptor for
1958 * the current user process.
1960 * If the descriptor doesn't exist, EBADF is returned.
1962 * If the descriptor exists but doesn't match 'flags' then
1963 * return EBADF for read attempts and EINVAL for write attempts.
1965 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1966 * It should be dropped with fdrop().
1967 * If it is not set, then the refcount will not be bumped however the
1968 * thread's filedesc struct will be returned locked (for fgetsock).
1970 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1971 * Otherwise *fpp is set and zero is returned.
1974 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1976 struct filedesc *fdp;
1980 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1983 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1984 FILEDESC_UNLOCK(fdp);
1989 * FREAD and FWRITE failure return EBADF as per POSIX.
1991 * Only one flag, or 0, may be specified.
1993 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1994 FILEDESC_UNLOCK(fdp);
1997 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1998 FILEDESC_UNLOCK(fdp);
2003 FILEDESC_UNLOCK(fdp);
2010 fget(struct thread *td, int fd, struct file **fpp)
2013 return(_fget(td, fd, fpp, 0, 1));
2017 fget_read(struct thread *td, int fd, struct file **fpp)
2020 return(_fget(td, fd, fpp, FREAD, 1));
2024 fget_write(struct thread *td, int fd, struct file **fpp)
2027 return(_fget(td, fd, fpp, FWRITE, 1));
2031 * Like fget() but loads the underlying vnode, or returns an error if
2032 * the descriptor does not represent a vnode. Note that pipes use vnodes
2033 * but never have VM objects. The returned vnode will be vref()d.
2035 * XXX: what about the unused flags ?
2038 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2044 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2046 if (fp->f_vnode == NULL) {
2052 FILEDESC_UNLOCK(td->td_proc->p_fd);
2057 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2060 return (_fgetvp(td, fd, vpp, 0));
2064 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2067 return (_fgetvp(td, fd, vpp, FREAD));
2072 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2075 return (_fgetvp(td, fd, vpp, FWRITE));
2080 * Like fget() but loads the underlying socket, or returns an error if
2081 * the descriptor does not represent a socket.
2083 * We bump the ref count on the returned socket. XXX Also obtain the SX
2084 * lock in the future.
2086 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2087 * on their file descriptor reference to prevent the socket from being
2091 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2101 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2103 if (fp->f_type != DTYPE_SOCKET) {
2108 *fflagp = fp->f_flag;
2113 FILEDESC_UNLOCK(td->td_proc->p_fd);
2118 * Drop the reference count on the socket and XXX release the SX lock in the
2119 * future. The last reference closes the socket.
2121 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2124 fputsock(struct socket *so)
2134 fdrop(struct file *fp, struct thread *td)
2138 return (fdrop_locked(fp, td));
2142 * Drop reference on struct file passed in, may call closef if the
2143 * reference hits zero.
2144 * Expects struct file locked, and will unlock it.
2147 fdrop_locked(struct file *fp, struct thread *td)
2151 FILE_LOCK_ASSERT(fp, MA_OWNED);
2153 if (--fp->f_count > 0) {
2159 * We might have just dropped the last reference to a file
2160 * object that is for a UNIX domain socket whose message
2161 * buffers are being examined in unp_gc(). If that is the
2162 * case, FWAIT will be set in f_gcflag and we need to wait for
2163 * unp_gc() to finish its scan.
2165 while (fp->f_gcflag & FWAIT)
2166 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2168 /* We have the last ref so we can proceed without the file lock. */
2170 if (fp->f_count < 0)
2171 panic("fdrop: count < 0");
2172 if (fp->f_ops != &badfileops)
2173 error = fo_close(fp, td);
2177 sx_xlock(&filelist_lock);
2178 LIST_REMOVE(fp, f_list);
2180 sx_xunlock(&filelist_lock);
2182 uma_zfree(file_zone, fp);
2188 * Apply an advisory lock on a file descriptor.
2190 * Just attempt to get a record lock of the requested type on the entire file
2191 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2193 #ifndef _SYS_SYSPROTO_H_
2201 flock(struct thread *td, struct flock_args *uap)
2208 if ((error = fget(td, uap->fd, &fp)) != 0)
2210 if (fp->f_type != DTYPE_VNODE) {
2212 return (EOPNOTSUPP);
2217 lf.l_whence = SEEK_SET;
2220 if (uap->how & LOCK_UN) {
2221 lf.l_type = F_UNLCK;
2223 fp->f_flag &= ~FHASLOCK;
2225 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2228 if (uap->how & LOCK_EX)
2229 lf.l_type = F_WRLCK;
2230 else if (uap->how & LOCK_SH)
2231 lf.l_type = F_RDLCK;
2237 fp->f_flag |= FHASLOCK;
2239 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2240 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2247 * Duplicate the specified descriptor to a free descriptor.
2250 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2256 * If the to-be-dup'd fd number is greater than the allowed number
2257 * of file descriptors, or the fd to be dup'd has already been
2258 * closed, then reject.
2261 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2262 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2263 FILEDESC_UNLOCK(fdp);
2268 * There are two cases of interest here.
2270 * For ENODEV simply dup (dfd) to file descriptor
2271 * (indx) and return.
2273 * For ENXIO steal away the file structure from (dfd) and
2274 * store it in (indx). (dfd) is effectively closed by
2277 * Any other error code is just returned.
2282 * Check that the mode the file is being opened for is a
2283 * subset of the mode of the existing descriptor.
2286 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2288 FILEDESC_UNLOCK(fdp);
2291 fp = fdp->fd_ofiles[indx];
2292 fdp->fd_ofiles[indx] = wfp;
2293 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2298 FILEDESC_UNLOCK(fdp);
2301 * We now own the reference to fp that the ofiles[]
2302 * array used to own. Release it.
2305 fdrop_locked(fp, td);
2311 * Steal away the file pointer from dfd and stuff it into indx.
2313 fp = fdp->fd_ofiles[indx];
2314 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2315 fdp->fd_ofiles[dfd] = NULL;
2316 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2317 fdp->fd_ofileflags[dfd] = 0;
2325 * We now own the reference to fp that the ofiles[] array
2326 * used to own. Release it.
2329 fdrop_locked(fp, td);
2331 FILEDESC_UNLOCK(fdp);
2336 FILEDESC_UNLOCK(fdp);
2343 * Scan all active processes to see if any of them have a current
2344 * or root directory of `olddp'. If so, replace them with the new
2348 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2350 struct filedesc *fdp;
2354 if (vrefcnt(olddp) == 1)
2356 sx_slock(&allproc_lock);
2357 FOREACH_PROC_IN_SYSTEM(p) {
2362 FILEDESC_LOCK_FAST(fdp);
2363 if (fdp->fd_cdir == olddp) {
2365 fdp->fd_cdir = newdp;
2368 if (fdp->fd_rdir == olddp) {
2370 fdp->fd_rdir = newdp;
2373 FILEDESC_UNLOCK_FAST(fdp);
2378 sx_sunlock(&allproc_lock);
2379 if (rootvnode == olddp) {
2386 struct filedesc_to_leader *
2387 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2389 struct filedesc_to_leader *fdtol;
2391 MALLOC(fdtol, struct filedesc_to_leader *,
2392 sizeof(struct filedesc_to_leader),
2393 M_FILEDESC_TO_LEADER,
2395 fdtol->fdl_refcount = 1;
2396 fdtol->fdl_holdcount = 0;
2397 fdtol->fdl_wakeup = 0;
2398 fdtol->fdl_leader = leader;
2401 fdtol->fdl_next = old->fdl_next;
2402 fdtol->fdl_prev = old;
2403 old->fdl_next = fdtol;
2404 fdtol->fdl_next->fdl_prev = fdtol;
2405 FILEDESC_UNLOCK(fdp);
2407 fdtol->fdl_next = fdtol;
2408 fdtol->fdl_prev = fdtol;
2414 * Get file structures.
2417 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2420 struct filedesc *fdp;
2426 * Note: because the number of file descriptors is calculated
2427 * in different ways for sizing vs returning the data,
2428 * there is information leakage from the first loop. However,
2429 * it is of a similar order of magnitude to the leakage from
2430 * global system statistics such as kern.openfiles.
2432 error = sysctl_wire_old_buffer(req, 0);
2435 if (req->oldptr == NULL) {
2436 n = 16; /* A slight overestimate. */
2437 sx_slock(&filelist_lock);
2438 LIST_FOREACH(fp, &filehead, f_list) {
2440 * We should grab the lock, but this is an
2441 * estimate, so does it really matter?
2443 /* mtx_lock(fp->f_mtxp); */
2445 /* mtx_unlock(f->f_mtxp); */
2447 sx_sunlock(&filelist_lock);
2448 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2451 bzero(&xf, sizeof(xf));
2452 xf.xf_size = sizeof(xf);
2453 sx_slock(&allproc_lock);
2454 FOREACH_PROC_IN_SYSTEM(p) {
2455 if (p->p_state == PRS_NEW)
2458 if (p_cansee(req->td, p) != 0) {
2462 xf.xf_pid = p->p_pid;
2463 xf.xf_uid = p->p_ucred->cr_uid;
2468 FILEDESC_LOCK_FAST(fdp);
2469 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2470 if ((fp = fdp->fd_ofiles[n]) == NULL)
2474 xf.xf_data = fp->f_data;
2475 xf.xf_vnode = fp->f_vnode;
2476 xf.xf_type = fp->f_type;
2477 xf.xf_count = fp->f_count;
2478 xf.xf_msgcount = fp->f_msgcount;
2479 xf.xf_offset = fp->f_offset;
2480 xf.xf_flag = fp->f_flag;
2481 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2485 FILEDESC_UNLOCK_FAST(fdp);
2490 sx_sunlock(&allproc_lock);
2494 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2495 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2499 * For the purposes of debugging, generate a human-readable string for the
2503 file_type_to_name(short type)
2529 * For the purposes of debugging, identify a process (if any, perhaps one of
2530 * many) that references the passed file in its file descriptor array. Return
2533 static struct proc *
2534 file_to_first_proc(struct file *fp)
2536 struct filedesc *fdp;
2540 FOREACH_PROC_IN_SYSTEM(p) {
2541 if (p->p_state == PRS_NEW)
2546 for (n = 0; n < fdp->fd_nfiles; n++) {
2547 if (fp == fdp->fd_ofiles[n])
2555 db_print_file(struct file *fp, int header)
2560 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
2561 "File", "Type", "Data", "Flag", "GCFl", "Count",
2562 "MCount", "Vnode", "FPID", "FCmd");
2563 p = file_to_first_proc(fp);
2564 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2565 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2566 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2567 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2570 DB_SHOW_COMMAND(file, db_show_file)
2575 db_printf("usage: show file <addr>\n");
2578 fp = (struct file *)addr;
2579 db_print_file(fp, 1);
2582 DB_SHOW_COMMAND(files, db_show_files)
2588 LIST_FOREACH(fp, &filehead, f_list) {
2589 db_print_file(fp, header);
2595 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2596 &maxfilesperproc, 0, "Maximum files allowed open per process");
2598 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2599 &maxfiles, 0, "Maximum number of files");
2601 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2602 &openfiles, 0, "System-wide number of open files");
2606 filelistinit(void *dummy)
2609 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2610 NULL, NULL, UMA_ALIGN_PTR, 0);
2611 sx_init(&filelist_lock, "filelist lock");
2612 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2613 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2615 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2617 /*-------------------------------------------------------------------*/
2620 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2627 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2634 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2641 badfo_kqfilter(struct file *fp, struct knote *kn)
2648 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2655 badfo_close(struct file *fp, struct thread *td)
2661 struct fileops badfileops = {
2662 .fo_read = badfo_readwrite,
2663 .fo_write = badfo_readwrite,
2664 .fo_ioctl = badfo_ioctl,
2665 .fo_poll = badfo_poll,
2666 .fo_kqfilter = badfo_kqfilter,
2667 .fo_stat = badfo_stat,
2668 .fo_close = badfo_close,
2672 /*-------------------------------------------------------------------*/
2675 * File Descriptor pseudo-device driver (/dev/fd/).
2677 * Opening minor device N dup()s the file (if any) connected to file
2678 * descriptor N belonging to the calling process. Note that this driver
2679 * consists of only the ``open()'' routine, because all subsequent
2680 * references to this file will be direct to the other driver.
2682 * XXX: we could give this one a cloning event handler if necessary.
2687 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2691 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2692 * the file descriptor being sought for duplication. The error
2693 * return ensures that the vnode for this device will be released
2694 * by vn_open. Open will detect this special error and take the
2695 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2696 * will simply report the error.
2698 td->td_dupfd = dev2unit(dev);
2702 static struct cdevsw fildesc_cdevsw = {
2703 .d_version = D_VERSION,
2704 .d_flags = D_NEEDGIANT,
2710 fildesc_drvinit(void *unused)
2714 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2715 make_dev_alias(dev, "stdin");
2716 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2717 make_dev_alias(dev, "stdout");
2718 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2719 make_dev_alias(dev, "stderr");
2722 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)