2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_compat.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
47 #include <sys/fcntl.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mqueue.h>
58 #include <sys/mutex.h>
59 #include <sys/namei.h>
61 #include <sys/resourcevar.h>
62 #include <sys/signalvar.h>
63 #include <sys/socketvar.h>
66 #include <sys/syscallsubr.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysproto.h>
69 #include <sys/unistd.h>
70 #include <sys/vnode.h>
76 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
77 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
78 "file desc to leader structures");
79 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
81 static uma_zone_t file_zone;
84 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
85 enum dup_type { DUP_VARIABLE, DUP_FIXED };
87 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
89 static int fd_first_free(struct filedesc *, int, int);
90 static int fd_last_used(struct filedesc *, int, int);
91 static void fdgrowtable(struct filedesc *, int);
92 static int fdrop_locked(struct file *fp, struct thread *td);
93 static void fdunused(struct filedesc *fdp, int fd);
94 static void fdused(struct filedesc *fdp, int fd);
97 * A process is initially started out with NDFILE descriptors stored within
98 * this structure, selected to be enough for typical applications based on
99 * the historical limit of 20 open files (and the usage of descriptors by
100 * shells). If these descriptors are exhausted, a larger descriptor table
101 * may be allocated, up to a process' resource limit; the internal arrays
105 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
106 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
107 #define NDSLOT(x) ((x) / NDENTRIES)
108 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
109 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
112 * Storage required per open file descriptor.
114 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
117 * Basic allocation of descriptors:
118 * one of the above, plus arrays for NDFILE descriptors.
121 struct filedesc fd_fd;
123 * These arrays are used when the number of open files is
124 * <= NDFILE, and are then pointed to by the pointers above.
126 struct file *fd_dfiles[NDFILE];
127 char fd_dfileflags[NDFILE];
128 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
132 * Descriptor management.
134 struct filelist filehead; /* head of list of open files */
135 int openfiles; /* actual number of open files */
136 struct sx filelist_lock; /* sx to protect filelist */
137 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
138 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
140 /* A mutex to protect the association between a proc and filedesc. */
141 static struct mtx fdesc_mtx;
144 * Find the first zero bit in the given bitmap, starting at low and not
145 * exceeding size - 1.
148 fd_first_free(struct filedesc *fdp, int low, int size)
150 NDSLOTTYPE *map = fdp->fd_map;
158 if (low % NDENTRIES) {
159 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
160 if ((mask &= ~map[off]) != 0UL)
161 return (off * NDENTRIES + ffsl(mask) - 1);
164 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
165 if (map[off] != ~0UL)
166 return (off * NDENTRIES + ffsl(~map[off]) - 1);
171 * Find the highest non-zero bit in the given bitmap, starting at low and
172 * not exceeding size - 1.
175 fd_last_used(struct filedesc *fdp, int low, int size)
177 NDSLOTTYPE *map = fdp->fd_map;
185 if (size % NDENTRIES) {
186 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
187 if ((mask &= map[off]) != 0)
188 return (off * NDENTRIES + flsl(mask) - 1);
191 for (minoff = NDSLOT(low); off >= minoff; --off)
193 return (off * NDENTRIES + flsl(map[off]) - 1);
198 fdisused(struct filedesc *fdp, int fd)
200 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
201 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
202 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
206 * Mark a file descriptor as used.
209 fdused(struct filedesc *fdp, int fd)
211 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
212 KASSERT(!fdisused(fdp, fd),
213 ("fd already used"));
214 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
215 if (fd > fdp->fd_lastfile)
216 fdp->fd_lastfile = fd;
217 if (fd == fdp->fd_freefile)
218 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
222 * Mark a file descriptor as unused.
225 fdunused(struct filedesc *fdp, int fd)
227 FILEDESC_LOCK_ASSERT(fdp, MA_OWNED);
228 KASSERT(fdisused(fdp, fd),
229 ("fd is already unused"));
230 KASSERT(fdp->fd_ofiles[fd] == NULL,
231 ("fd is still in use"));
232 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
233 if (fd < fdp->fd_freefile)
234 fdp->fd_freefile = fd;
235 if (fd == fdp->fd_lastfile)
236 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
240 * System calls on descriptors.
242 #ifndef _SYS_SYSPROTO_H_
243 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_
280 dup2(struct thread *td, struct dup2_args *uap)
283 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
288 * Duplicate a file descriptor.
290 #ifndef _SYS_SYSPROTO_H_
300 dup(struct thread *td, struct dup_args *uap)
303 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
307 * The file control system call.
309 #ifndef _SYS_SYSPROTO_H_
321 fcntl(struct thread *td, struct fcntl_args *uap)
332 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
341 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
344 if (uap->cmd == F_GETLK)
345 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
350 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
352 struct filedesc *fdp;
363 * XXXRW: Some fcntl() calls require Giant -- others don't. Try to
364 * avoid grabbing Giant for calls we know don't need it.
384 if ((unsigned)fd >= fdp->fd_nfiles ||
385 (fp = fdp->fd_ofiles[fd]) == NULL) {
386 FILEDESC_UNLOCK(fdp);
390 pop = &fdp->fd_ofileflags[fd];
394 /* mtx_assert(&Giant, MA_NOTOWNED); */
395 FILEDESC_UNLOCK(fdp);
398 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
399 newmin >= maxfilesperproc) {
405 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
409 /* mtx_assert(&Giant, MA_NOTOWNED); */
410 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
411 FILEDESC_UNLOCK(fdp);
415 /* mtx_assert(&Giant, MA_NOTOWNED); */
416 *pop = (*pop &~ UF_EXCLOSE) |
417 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
418 FILEDESC_UNLOCK(fdp);
422 /* mtx_assert(&Giant, MA_NOTOWNED); */
424 td->td_retval[0] = OFLAGS(fp->f_flag);
426 FILEDESC_UNLOCK(fdp);
430 mtx_assert(&Giant, MA_OWNED);
433 fp->f_flag &= ~FCNTLFLAGS;
434 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
436 FILEDESC_UNLOCK(fdp);
437 tmp = fp->f_flag & FNONBLOCK;
438 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
443 tmp = fp->f_flag & FASYNC;
444 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
450 fp->f_flag &= ~FNONBLOCK;
453 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
458 mtx_assert(&Giant, MA_OWNED);
460 FILEDESC_UNLOCK(fdp);
461 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
463 td->td_retval[0] = tmp;
468 mtx_assert(&Giant, MA_OWNED);
470 FILEDESC_UNLOCK(fdp);
472 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
477 mtx_assert(&Giant, MA_OWNED);
479 /* FALLTHROUGH F_SETLK */
482 mtx_assert(&Giant, MA_OWNED);
483 if (fp->f_type != DTYPE_VNODE) {
484 FILEDESC_UNLOCK(fdp);
489 flp = (struct flock *)arg;
490 if (flp->l_whence == SEEK_CUR) {
491 if (fp->f_offset < 0 ||
493 fp->f_offset > OFF_MAX - flp->l_start)) {
494 FILEDESC_UNLOCK(fdp);
498 flp->l_start += fp->f_offset;
502 * VOP_ADVLOCK() may block.
505 FILEDESC_UNLOCK(fdp);
508 switch (flp->l_type) {
510 if ((fp->f_flag & FREAD) == 0) {
514 PROC_LOCK(p->p_leader);
515 p->p_leader->p_flag |= P_ADVLOCK;
516 PROC_UNLOCK(p->p_leader);
517 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
521 if ((fp->f_flag & FWRITE) == 0) {
525 PROC_LOCK(p->p_leader);
526 p->p_leader->p_flag |= P_ADVLOCK;
527 PROC_UNLOCK(p->p_leader);
528 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
532 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
539 /* Check for race with close */
540 FILEDESC_LOCK_FAST(fdp);
541 if ((unsigned) fd >= fdp->fd_nfiles ||
542 fp != fdp->fd_ofiles[fd]) {
543 FILEDESC_UNLOCK_FAST(fdp);
544 flp->l_whence = SEEK_SET;
547 flp->l_type = F_UNLCK;
548 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
549 F_UNLCK, flp, F_POSIX);
551 FILEDESC_UNLOCK_FAST(fdp);
556 mtx_assert(&Giant, MA_OWNED);
557 if (fp->f_type != DTYPE_VNODE) {
558 FILEDESC_UNLOCK(fdp);
562 flp = (struct flock *)arg;
563 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
564 flp->l_type != F_UNLCK) {
565 FILEDESC_UNLOCK(fdp);
569 if (flp->l_whence == SEEK_CUR) {
570 if ((flp->l_start > 0 &&
571 fp->f_offset > OFF_MAX - flp->l_start) ||
573 fp->f_offset < OFF_MIN - flp->l_start)) {
574 FILEDESC_UNLOCK(fdp);
578 flp->l_start += fp->f_offset;
581 * VOP_ADVLOCK() may block.
584 FILEDESC_UNLOCK(fdp);
586 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
591 FILEDESC_UNLOCK(fdp);
602 * Common code for dup, dup2, and fcntl(F_DUPFD).
605 do_dup(struct thread *td, enum dup_type type, int old, int new, register_t *retval)
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_UNLOCK(fdp);
636 if (type == DUP_FIXED && old == new) {
638 FILEDESC_UNLOCK(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_UNLOCK(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_UNLOCK(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_UNLOCK(fdp);
721 (void) closef(delfp, td);
723 FILEDESC_LOCK_FAST(fdp);
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_UNLOCK_FAST(fdp);
733 FILEDESC_UNLOCK(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_
972 struct close_args *uap;
974 struct filedesc *fdp;
982 fdp = td->td_proc->p_fd;
984 if ((unsigned)fd >= fdp->fd_nfiles ||
985 (fp = fdp->fd_ofiles[fd]) == NULL) {
986 FILEDESC_UNLOCK(fdp);
989 fdp->fd_ofiles[fd] = NULL;
990 fdp->fd_ofileflags[fd] = 0;
992 if (td->td_proc->p_fdtol != NULL) {
994 * Ask fdfree() to sleep to ensure that all relevant
995 * process leaders can be traversed in closef().
997 fdp->fd_holdleaderscount++;
1002 * We now hold the fp reference that used to be owned by the descriptor
1004 * We have to unlock the FILEDESC *AFTER* knote_fdclose to prevent a
1005 * race of the fd getting opened, a knote added, and deleteing a knote
1008 knote_fdclose(td, fd);
1009 if (fp->f_type == DTYPE_MQUEUE)
1010 mq_fdclose(td, fd, fp);
1011 FILEDESC_UNLOCK(fdp);
1013 error = closef(fp, td);
1015 FILEDESC_LOCK_FAST(fdp);
1016 fdp->fd_holdleaderscount--;
1017 if (fdp->fd_holdleaderscount == 0 &&
1018 fdp->fd_holdleaderswakeup != 0) {
1019 fdp->fd_holdleaderswakeup = 0;
1020 wakeup(&fdp->fd_holdleaderscount);
1022 FILEDESC_UNLOCK_FAST(fdp);
1027 #if defined(COMPAT_43)
1029 * Return status information about a file descriptor.
1031 #ifndef _SYS_SYSPROTO_H_
1032 struct ofstat_args {
1042 ofstat(struct thread *td, struct ofstat_args *uap)
1048 error = kern_fstat(td, uap->fd, &ub);
1051 error = copyout(&oub, uap->sb, sizeof(oub));
1055 #endif /* COMPAT_43 */
1058 * Return status information about a file descriptor.
1060 #ifndef _SYS_SYSPROTO_H_
1071 fstat(struct thread *td, struct fstat_args *uap)
1076 error = kern_fstat(td, uap->fd, &ub);
1078 error = copyout(&ub, uap->sb, sizeof(ub));
1083 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1088 if ((error = fget(td, fd, &fp)) != 0)
1090 error = fo_stat(fp, sbp, td->td_ucred, td);
1096 * Return status information about a file descriptor.
1098 #ifndef _SYS_SYSPROTO_H_
1099 struct nfstat_args {
1109 nfstat(struct thread *td, struct nfstat_args *uap)
1115 error = kern_fstat(td, uap->fd, &ub);
1117 cvtnstat(&ub, &nub);
1118 error = copyout(&nub, uap->sb, sizeof(nub));
1124 * Return pathconf information about a file descriptor.
1126 #ifndef _SYS_SYSPROTO_H_
1127 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_LOCK_ASSERT(fdp, MA_OWNED);
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_UNLOCK(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);
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_LOCK_ASSERT(fdp, MA_OWNED);
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
1288 * are available to the process p.
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, MA_OWNED);
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
1316 * a file decriptor for the process that refers to it.
1317 * We add one reference to the file for the descriptor table
1318 * and one reference for resultfp. This is to prevent us being
1319 * preempted and the entry in the descriptor table closed after
1320 * we release the FILEDESC lock.
1323 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1325 struct proc *p = td->td_proc;
1326 struct file *fp, *fq;
1328 int maxuserfiles = maxfiles - (maxfiles / 20);
1329 static struct timeval lastfail;
1332 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1333 sx_xlock(&filelist_lock);
1334 if ((openfiles >= maxuserfiles && (td->td_ucred->cr_ruid != 0 ||
1335 jailed(td->td_ucred))) || openfiles >= maxfiles) {
1336 if (ppsratecheck(&lastfail, &curfail, 1)) {
1337 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1338 td->td_ucred->cr_ruid);
1340 sx_xunlock(&filelist_lock);
1341 uma_zfree(file_zone, fp);
1347 * If the process has file descriptor zero open, add the new file
1348 * descriptor to the list of open files at that point, otherwise
1349 * put it at the front of the list of open files.
1351 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1355 fp->f_cred = crhold(td->td_ucred);
1356 fp->f_ops = &badfileops;
1359 FILEDESC_LOCK(p->p_fd);
1360 if ((fq = p->p_fd->fd_ofiles[0])) {
1361 LIST_INSERT_AFTER(fq, fp, f_list);
1363 LIST_INSERT_HEAD(&filehead, fp, f_list);
1365 sx_xunlock(&filelist_lock);
1366 if ((error = fdalloc(td, 0, &i))) {
1367 FILEDESC_UNLOCK(p->p_fd);
1373 p->p_fd->fd_ofiles[i] = fp;
1374 FILEDESC_UNLOCK(p->p_fd);
1383 * Build a new filedesc structure from another.
1384 * Copy the current, root, and jail root vnode references.
1387 fdinit(struct filedesc *fdp)
1389 struct filedesc0 *newfdp;
1391 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1392 mtx_init(&newfdp->fd_fd.fd_mtx, FILEDESC_LOCK_DESC, NULL, MTX_DEF);
1395 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1396 if (newfdp->fd_fd.fd_cdir)
1397 VREF(newfdp->fd_fd.fd_cdir);
1398 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1399 if (newfdp->fd_fd.fd_rdir)
1400 VREF(newfdp->fd_fd.fd_rdir);
1401 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1402 if (newfdp->fd_fd.fd_jdir)
1403 VREF(newfdp->fd_fd.fd_jdir);
1404 FILEDESC_UNLOCK(fdp);
1407 /* Create the file descriptor table. */
1408 newfdp->fd_fd.fd_refcnt = 1;
1409 newfdp->fd_fd.fd_holdcnt = 1;
1410 newfdp->fd_fd.fd_cmask = CMASK;
1411 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1412 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1413 newfdp->fd_fd.fd_nfiles = NDFILE;
1414 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1415 return (&newfdp->fd_fd);
1418 static struct filedesc *
1419 fdhold(struct proc *p)
1421 struct filedesc *fdp;
1423 mtx_lock(&fdesc_mtx);
1427 mtx_unlock(&fdesc_mtx);
1432 fddrop(struct filedesc *fdp)
1436 mtx_lock(&fdesc_mtx);
1437 i = --fdp->fd_holdcnt;
1438 mtx_unlock(&fdesc_mtx);
1442 mtx_destroy(&fdp->fd_mtx);
1443 FREE(fdp, M_FILEDESC);
1447 * Share a filedesc structure.
1450 fdshare(struct filedesc *fdp)
1452 FILEDESC_LOCK_FAST(fdp);
1454 FILEDESC_UNLOCK_FAST(fdp);
1459 * Unshare a filedesc structure, if necessary by making a copy
1462 fdunshare(struct proc *p, struct thread *td)
1465 FILEDESC_LOCK_FAST(p->p_fd);
1466 if (p->p_fd->fd_refcnt > 1) {
1467 struct filedesc *tmp;
1469 FILEDESC_UNLOCK_FAST(p->p_fd);
1470 tmp = fdcopy(p->p_fd);
1474 FILEDESC_UNLOCK_FAST(p->p_fd);
1478 * Copy a filedesc structure.
1479 * A NULL pointer in returns a NULL reference, this is to ease callers,
1483 fdcopy(struct filedesc *fdp)
1485 struct filedesc *newfdp;
1488 /* Certain daemons might not have file descriptors. */
1492 newfdp = fdinit(fdp);
1493 FILEDESC_LOCK_FAST(fdp);
1494 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1495 FILEDESC_UNLOCK_FAST(fdp);
1496 FILEDESC_LOCK(newfdp);
1497 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1498 FILEDESC_UNLOCK(newfdp);
1499 FILEDESC_LOCK_FAST(fdp);
1501 /* copy everything except kqueue descriptors */
1502 newfdp->fd_freefile = -1;
1503 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1504 if (fdisused(fdp, i) &&
1505 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1506 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1507 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1508 fhold(newfdp->fd_ofiles[i]);
1509 newfdp->fd_lastfile = i;
1511 if (newfdp->fd_freefile == -1)
1512 newfdp->fd_freefile = i;
1515 FILEDESC_UNLOCK_FAST(fdp);
1516 FILEDESC_LOCK(newfdp);
1517 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1518 if (newfdp->fd_ofiles[i] != NULL)
1520 FILEDESC_UNLOCK(newfdp);
1521 FILEDESC_LOCK_FAST(fdp);
1522 if (newfdp->fd_freefile == -1)
1523 newfdp->fd_freefile = i;
1524 newfdp->fd_cmask = fdp->fd_cmask;
1525 FILEDESC_UNLOCK_FAST(fdp);
1530 * Release a filedesc structure.
1533 fdfree(struct thread *td)
1535 struct filedesc *fdp;
1538 struct filedesc_to_leader *fdtol;
1540 struct vnode *cdir, *jdir, *rdir, *vp;
1543 /* Certain daemons might not have file descriptors. */
1544 fdp = td->td_proc->p_fd;
1548 /* Check for special need to clear POSIX style locks */
1549 fdtol = td->td_proc->p_fdtol;
1550 if (fdtol != NULL) {
1552 KASSERT(fdtol->fdl_refcount > 0,
1553 ("filedesc_to_refcount botch: fdl_refcount=%d",
1554 fdtol->fdl_refcount));
1555 if (fdtol->fdl_refcount == 1 &&
1556 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1557 for (i = 0, fpp = fdp->fd_ofiles;
1558 i <= fdp->fd_lastfile;
1561 (*fpp)->f_type != DTYPE_VNODE)
1565 FILEDESC_UNLOCK(fdp);
1566 lf.l_whence = SEEK_SET;
1569 lf.l_type = F_UNLCK;
1571 locked = VFS_LOCK_GIANT(vp->v_mount);
1572 (void) VOP_ADVLOCK(vp,
1573 (caddr_t)td->td_proc->
1578 VFS_UNLOCK_GIANT(locked);
1581 fpp = fdp->fd_ofiles + i;
1585 if (fdtol->fdl_refcount == 1) {
1586 if (fdp->fd_holdleaderscount > 0 &&
1587 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1589 * close() or do_dup() has cleared a reference
1590 * in a shared file descriptor table.
1592 fdp->fd_holdleaderswakeup = 1;
1593 msleep(&fdp->fd_holdleaderscount, &fdp->fd_mtx,
1594 PLOCK, "fdlhold", 0);
1597 if (fdtol->fdl_holdcount > 0) {
1599 * Ensure that fdtol->fdl_leader
1600 * remains valid in closef().
1602 fdtol->fdl_wakeup = 1;
1603 msleep(fdtol, &fdp->fd_mtx,
1604 PLOCK, "fdlhold", 0);
1608 fdtol->fdl_refcount--;
1609 if (fdtol->fdl_refcount == 0 &&
1610 fdtol->fdl_holdcount == 0) {
1611 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1612 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1615 td->td_proc->p_fdtol = NULL;
1616 FILEDESC_UNLOCK(fdp);
1618 FREE(fdtol, M_FILEDESC_TO_LEADER);
1620 FILEDESC_LOCK_FAST(fdp);
1621 i = --fdp->fd_refcnt;
1622 FILEDESC_UNLOCK_FAST(fdp);
1626 * We are the last reference to the structure, so we can
1627 * safely assume it will not change out from under us.
1629 fpp = fdp->fd_ofiles;
1630 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1632 (void) closef(*fpp, td);
1636 /* XXX This should happen earlier. */
1637 mtx_lock(&fdesc_mtx);
1638 td->td_proc->p_fd = NULL;
1639 mtx_unlock(&fdesc_mtx);
1641 if (fdp->fd_nfiles > NDFILE)
1642 FREE(fdp->fd_ofiles, M_FILEDESC);
1643 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1644 FREE(fdp->fd_map, M_FILEDESC);
1648 cdir = fdp->fd_cdir;
1649 fdp->fd_cdir = NULL;
1650 rdir = fdp->fd_rdir;
1651 fdp->fd_rdir = NULL;
1652 jdir = fdp->fd_jdir;
1653 fdp->fd_jdir = NULL;
1654 FILEDESC_UNLOCK(fdp);
1657 locked = VFS_LOCK_GIANT(cdir->v_mount);
1659 VFS_UNLOCK_GIANT(locked);
1662 locked = VFS_LOCK_GIANT(rdir->v_mount);
1664 VFS_UNLOCK_GIANT(locked);
1667 locked = VFS_LOCK_GIANT(jdir->v_mount);
1669 VFS_UNLOCK_GIANT(locked);
1676 * For setugid programs, we don't want to people to use that setugidness
1677 * to generate error messages which write to a file which otherwise would
1678 * otherwise be off-limits to the process. We check for filesystems where
1679 * the vnode can change out from under us after execve (like [lin]procfs).
1681 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1682 * sufficient. We also don't check for setugidness since we know we are.
1685 is_unsafe(struct file *fp)
1687 if (fp->f_type == DTYPE_VNODE) {
1688 struct vnode *vp = fp->f_vnode;
1690 if ((vp->v_vflag & VV_PROCDEP) != 0)
1697 * Make this setguid thing safe, if at all possible.
1700 setugidsafety(struct thread *td)
1702 struct filedesc *fdp;
1705 /* Certain daemons might not have file descriptors. */
1706 fdp = td->td_proc->p_fd;
1711 * Note: fdp->fd_ofiles may be reallocated out from under us while
1712 * we are blocked in a close. Be careful!
1715 for (i = 0; i <= fdp->fd_lastfile; i++) {
1718 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1721 knote_fdclose(td, i);
1723 * NULL-out descriptor prior to close to avoid
1724 * a race while close blocks.
1726 fp = fdp->fd_ofiles[i];
1727 fdp->fd_ofiles[i] = NULL;
1728 fdp->fd_ofileflags[i] = 0;
1730 FILEDESC_UNLOCK(fdp);
1731 (void) closef(fp, td);
1735 FILEDESC_UNLOCK(fdp);
1739 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1743 if (fdp->fd_ofiles[idx] == fp) {
1744 fdp->fd_ofiles[idx] = NULL;
1746 FILEDESC_UNLOCK(fdp);
1749 FILEDESC_UNLOCK(fdp);
1754 * Close any files on exec?
1757 fdcloseexec(struct thread *td)
1759 struct filedesc *fdp;
1762 /* Certain daemons might not have file descriptors. */
1763 fdp = td->td_proc->p_fd;
1770 * We cannot cache fd_ofiles or fd_ofileflags since operations
1771 * may block and rip them out from under us.
1773 for (i = 0; i <= fdp->fd_lastfile; i++) {
1774 if (fdp->fd_ofiles[i] != NULL &&
1775 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1776 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1779 knote_fdclose(td, i);
1781 * NULL-out descriptor prior to close to avoid
1782 * a race while close blocks.
1784 fp = fdp->fd_ofiles[i];
1785 fdp->fd_ofiles[i] = NULL;
1786 fdp->fd_ofileflags[i] = 0;
1788 if (fp->f_type == DTYPE_MQUEUE)
1789 mq_fdclose(td, i, fp);
1790 FILEDESC_UNLOCK(fdp);
1791 (void) closef(fp, td);
1795 FILEDESC_UNLOCK(fdp);
1799 * It is unsafe for set[ug]id processes to be started with file
1800 * descriptors 0..2 closed, as these descriptors are given implicit
1801 * significance in the Standard C library. fdcheckstd() will create a
1802 * descriptor referencing /dev/null for each of stdin, stdout, and
1803 * stderr that is not already open.
1806 fdcheckstd(struct thread *td)
1808 struct nameidata nd;
1809 struct filedesc *fdp;
1812 int fd, i, error, flags, devnull;
1814 fdp = td->td_proc->p_fd;
1817 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1820 for (i = 0; i < 3; i++) {
1821 if (fdp->fd_ofiles[i] != NULL)
1825 error = falloc(td, &fp, &fd);
1828 /* Note extra ref on `fp' held for us by falloc(). */
1829 KASSERT(fd == i, ("oof, we didn't get our fd"));
1830 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE,
1832 flags = FREAD | FWRITE;
1833 error = vn_open(&nd, &flags, 0, fd);
1836 * Someone may have closed the entry in the
1837 * file descriptor table, so check it hasn't
1838 * changed before dropping the reference count.
1841 KASSERT(fdp->fd_ofiles[fd] == fp,
1842 ("table not shared, how did it change?"));
1843 fdp->fd_ofiles[fd] = NULL;
1845 FILEDESC_UNLOCK(fdp);
1850 vfslocked = NDHASGIANT(&nd);
1851 NDFREE(&nd, NDF_ONLY_PNBUF);
1853 fp->f_vnode = nd.ni_vp;
1854 if (fp->f_data == NULL)
1855 fp->f_data = nd.ni_vp;
1856 if (fp->f_ops == &badfileops)
1858 fp->f_type = DTYPE_VNODE;
1859 VOP_UNLOCK(nd.ni_vp, 0, td);
1860 VFS_UNLOCK_GIANT(vfslocked);
1864 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1873 * Internal form of close.
1874 * Decrement reference count on file structure.
1875 * Note: td may be NULL when closing a file that was being passed in a
1878 * XXXRW: Giant is not required for the caller, but often will be held; this
1879 * makes it moderately likely the Giant will be recursed in the VFS case.
1882 closef(struct file *fp, struct thread *td)
1886 struct filedesc_to_leader *fdtol;
1887 struct filedesc *fdp;
1890 * POSIX record locking dictates that any close releases ALL
1891 * locks owned by this process. This is handled by setting
1892 * a flag in the unlock to free ONLY locks obeying POSIX
1893 * semantics, and not to free BSD-style file locks.
1894 * If the descriptor was in a message, POSIX-style locks
1895 * aren't passed with the descriptor, and the thread pointer
1896 * will be NULL. Callers should be careful only to pass a
1897 * NULL thread pointer when there really is no owning
1898 * context that might have locks, or the locks will be
1901 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1905 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1906 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1907 lf.l_whence = SEEK_SET;
1910 lf.l_type = F_UNLCK;
1911 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1912 F_UNLCK, &lf, F_POSIX);
1914 fdtol = td->td_proc->p_fdtol;
1915 if (fdtol != NULL) {
1917 * Handle special case where file descriptor table
1918 * is shared between multiple process leaders.
1920 fdp = td->td_proc->p_fd;
1922 for (fdtol = fdtol->fdl_next;
1923 fdtol != td->td_proc->p_fdtol;
1924 fdtol = fdtol->fdl_next) {
1925 if ((fdtol->fdl_leader->p_flag &
1928 fdtol->fdl_holdcount++;
1929 FILEDESC_UNLOCK(fdp);
1930 lf.l_whence = SEEK_SET;
1933 lf.l_type = F_UNLCK;
1935 (void) VOP_ADVLOCK(vp,
1936 (caddr_t)fdtol->fdl_leader,
1937 F_UNLCK, &lf, F_POSIX);
1939 fdtol->fdl_holdcount--;
1940 if (fdtol->fdl_holdcount == 0 &&
1941 fdtol->fdl_wakeup != 0) {
1942 fdtol->fdl_wakeup = 0;
1946 FILEDESC_UNLOCK(fdp);
1948 VFS_UNLOCK_GIANT(vfslocked);
1950 return (fdrop(fp, td));
1954 * Extract the file pointer associated with the specified descriptor for
1955 * the current user process.
1957 * If the descriptor doesn't exist, EBADF is returned.
1959 * If the descriptor exists but doesn't match 'flags' then
1960 * return EBADF for read attempts and EINVAL for write attempts.
1962 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1963 * It should be dropped with fdrop().
1964 * If it is not set, then the refcount will not be bumped however the
1965 * thread's filedesc struct will be returned locked (for fgetsock).
1967 * If an error occured the non-zero error is returned and *fpp is set to NULL.
1968 * Otherwise *fpp is set and zero is returned.
1971 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1973 struct filedesc *fdp;
1977 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1980 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1981 FILEDESC_UNLOCK(fdp);
1986 * FREAD and FWRITE failure return EBADF as per POSIX.
1988 * Only one flag, or 0, may be specified.
1990 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1991 FILEDESC_UNLOCK(fdp);
1994 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
1995 FILEDESC_UNLOCK(fdp);
2000 FILEDESC_UNLOCK(fdp);
2007 fget(struct thread *td, int fd, struct file **fpp)
2010 return(_fget(td, fd, fpp, 0, 1));
2014 fget_read(struct thread *td, int fd, struct file **fpp)
2017 return(_fget(td, fd, fpp, FREAD, 1));
2021 fget_write(struct thread *td, int fd, struct file **fpp)
2024 return(_fget(td, fd, fpp, FWRITE, 1));
2028 * Like fget() but loads the underlying vnode, or returns an error if
2029 * the descriptor does not represent a vnode. Note that pipes use vnodes
2030 * but never have VM objects. The returned vnode will be vref()d.
2032 * XXX: what about the unused flags ?
2035 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2041 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2043 if (fp->f_vnode == NULL) {
2049 FILEDESC_UNLOCK(td->td_proc->p_fd);
2054 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2057 return (_fgetvp(td, fd, vpp, 0));
2061 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2064 return (_fgetvp(td, fd, vpp, FREAD));
2069 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2072 return (_fgetvp(td, fd, vpp, FWRITE));
2077 * Like fget() but loads the underlying socket, or returns an error if
2078 * the descriptor does not represent a socket.
2080 * We bump the ref count on the returned socket. XXX Also obtain the SX
2081 * lock in the future.
2084 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2094 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2096 if (fp->f_type != DTYPE_SOCKET) {
2101 *fflagp = fp->f_flag;
2106 FILEDESC_UNLOCK(td->td_proc->p_fd);
2111 * Drop the reference count on the socket and XXX release the SX lock in
2112 * the future. The last reference closes the socket.
2115 fputsock(struct socket *so)
2125 fdrop(struct file *fp, struct thread *td)
2129 return (fdrop_locked(fp, td));
2133 * Drop reference on struct file passed in, may call closef if the
2134 * reference hits zero.
2135 * Expects struct file locked, and will unlock it.
2138 fdrop_locked(struct file *fp, struct thread *td)
2142 FILE_LOCK_ASSERT(fp, MA_OWNED);
2144 if (--fp->f_count > 0) {
2148 /* We have the last ref so we can proceed without the file lock. */
2150 if (fp->f_count < 0)
2151 panic("fdrop: count < 0");
2152 if (fp->f_ops != &badfileops)
2153 error = fo_close(fp, td);
2157 sx_xlock(&filelist_lock);
2158 LIST_REMOVE(fp, f_list);
2160 sx_xunlock(&filelist_lock);
2162 uma_zfree(file_zone, fp);
2168 * Apply an advisory lock on a file descriptor.
2170 * Just attempt to get a record lock of the requested type on
2171 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2173 #ifndef _SYS_SYSPROTO_H_
2184 flock(struct thread *td, struct flock_args *uap)
2191 if ((error = fget(td, uap->fd, &fp)) != 0)
2193 if (fp->f_type != DTYPE_VNODE) {
2195 return (EOPNOTSUPP);
2200 lf.l_whence = SEEK_SET;
2203 if (uap->how & LOCK_UN) {
2204 lf.l_type = F_UNLCK;
2206 fp->f_flag &= ~FHASLOCK;
2208 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2211 if (uap->how & LOCK_EX)
2212 lf.l_type = F_WRLCK;
2213 else if (uap->how & LOCK_SH)
2214 lf.l_type = F_RDLCK;
2220 fp->f_flag |= FHASLOCK;
2222 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2223 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2230 * Duplicate the specified descriptor to a free descriptor.
2233 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2239 * If the to-be-dup'd fd number is greater than the allowed number
2240 * of file descriptors, or the fd to be dup'd has already been
2241 * closed, then reject.
2244 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2245 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2246 FILEDESC_UNLOCK(fdp);
2251 * There are two cases of interest here.
2253 * For ENODEV simply dup (dfd) to file descriptor
2254 * (indx) and return.
2256 * For ENXIO steal away the file structure from (dfd) and
2257 * store it in (indx). (dfd) is effectively closed by
2260 * Any other error code is just returned.
2265 * Check that the mode the file is being opened for is a
2266 * subset of the mode of the existing descriptor.
2269 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2271 FILEDESC_UNLOCK(fdp);
2274 fp = fdp->fd_ofiles[indx];
2275 fdp->fd_ofiles[indx] = wfp;
2276 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2281 FILEDESC_UNLOCK(fdp);
2284 * We now own the reference to fp that the ofiles[]
2285 * array used to own. Release it.
2288 fdrop_locked(fp, td);
2294 * Steal away the file pointer from dfd and stuff it into indx.
2296 fp = fdp->fd_ofiles[indx];
2297 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2298 fdp->fd_ofiles[dfd] = NULL;
2299 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2300 fdp->fd_ofileflags[dfd] = 0;
2308 * We now own the reference to fp that the ofiles[] array
2309 * used to own. Release it.
2312 fdrop_locked(fp, td);
2314 FILEDESC_UNLOCK(fdp);
2319 FILEDESC_UNLOCK(fdp);
2326 * Scan all active processes to see if any of them have a current
2327 * or root directory of `olddp'. If so, replace them with the new
2331 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2333 struct filedesc *fdp;
2337 if (vrefcnt(olddp) == 1)
2339 sx_slock(&allproc_lock);
2340 LIST_FOREACH(p, &allproc, p_list) {
2345 FILEDESC_LOCK_FAST(fdp);
2346 if (fdp->fd_cdir == olddp) {
2348 fdp->fd_cdir = newdp;
2351 if (fdp->fd_rdir == olddp) {
2353 fdp->fd_rdir = newdp;
2356 FILEDESC_UNLOCK_FAST(fdp);
2361 sx_sunlock(&allproc_lock);
2362 if (rootvnode == olddp) {
2369 struct filedesc_to_leader *
2370 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2372 struct filedesc_to_leader *fdtol;
2374 MALLOC(fdtol, struct filedesc_to_leader *,
2375 sizeof(struct filedesc_to_leader),
2376 M_FILEDESC_TO_LEADER,
2378 fdtol->fdl_refcount = 1;
2379 fdtol->fdl_holdcount = 0;
2380 fdtol->fdl_wakeup = 0;
2381 fdtol->fdl_leader = leader;
2384 fdtol->fdl_next = old->fdl_next;
2385 fdtol->fdl_prev = old;
2386 old->fdl_next = fdtol;
2387 fdtol->fdl_next->fdl_prev = fdtol;
2388 FILEDESC_UNLOCK(fdp);
2390 fdtol->fdl_next = fdtol;
2391 fdtol->fdl_prev = fdtol;
2397 * Get file structures.
2400 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2403 struct filedesc *fdp;
2409 * Note: because the number of file descriptors is calculated
2410 * in different ways for sizing vs returning the data,
2411 * there is information leakage from the first loop. However,
2412 * it is of a similar order of magnitude to the leakage from
2413 * global system statistics such as kern.openfiles.
2415 error = sysctl_wire_old_buffer(req, 0);
2418 if (req->oldptr == NULL) {
2419 n = 16; /* A slight overestimate. */
2420 sx_slock(&filelist_lock);
2421 LIST_FOREACH(fp, &filehead, f_list) {
2423 * We should grab the lock, but this is an
2424 * estimate, so does it really matter?
2426 /* mtx_lock(fp->f_mtxp); */
2428 /* mtx_unlock(f->f_mtxp); */
2430 sx_sunlock(&filelist_lock);
2431 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2434 bzero(&xf, sizeof(xf));
2435 xf.xf_size = sizeof(xf);
2436 sx_slock(&allproc_lock);
2437 LIST_FOREACH(p, &allproc, p_list) {
2438 if (p->p_state == PRS_NEW)
2441 if (p_cansee(req->td, p) != 0) {
2445 xf.xf_pid = p->p_pid;
2446 xf.xf_uid = p->p_ucred->cr_uid;
2451 FILEDESC_LOCK_FAST(fdp);
2452 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2453 if ((fp = fdp->fd_ofiles[n]) == NULL)
2457 xf.xf_data = fp->f_data;
2458 xf.xf_vnode = fp->f_vnode;
2459 xf.xf_type = fp->f_type;
2460 xf.xf_count = fp->f_count;
2461 xf.xf_msgcount = fp->f_msgcount;
2462 xf.xf_offset = fp->f_offset;
2463 xf.xf_flag = fp->f_flag;
2464 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2468 FILEDESC_UNLOCK_FAST(fdp);
2473 sx_sunlock(&allproc_lock);
2477 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2478 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2482 * For the purposes of debugging, generate a human-readable string for the
2486 file_type_to_name(short type)
2508 * For the purposes of debugging, identify a process (if any, perhaps one of
2509 * many) that references the passed file in its file descriptor array. Return
2512 static struct proc *
2513 file_to_first_proc(struct file *fp)
2515 struct filedesc *fdp;
2519 LIST_FOREACH(p, &allproc, p_list) {
2520 if (p->p_state == PRS_NEW)
2525 for (n = 0; n < fdp->fd_nfiles; n++) {
2526 if (fp == fdp->fd_ofiles[n])
2533 DB_SHOW_COMMAND(files, db_show_files)
2538 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", "File",
2539 "Type", "Data", "Flag", "GCFl", "Count", "MCount", "Vnode",
2541 LIST_FOREACH(fp, &filehead, f_list) {
2542 p = file_to_first_proc(fp);
2543 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2544 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2545 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2546 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2551 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2552 &maxfilesperproc, 0, "Maximum files allowed open per process");
2554 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2555 &maxfiles, 0, "Maximum number of files");
2557 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2558 &openfiles, 0, "System-wide number of open files");
2562 filelistinit(void *dummy)
2565 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2566 NULL, NULL, UMA_ALIGN_PTR, 0);
2567 sx_init(&filelist_lock, "filelist lock");
2568 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2569 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2571 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2573 /*-------------------------------------------------------------------*/
2576 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2583 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2590 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2597 badfo_kqfilter(struct file *fp, struct knote *kn)
2604 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2611 badfo_close(struct file *fp, struct thread *td)
2617 struct fileops badfileops = {
2618 .fo_read = badfo_readwrite,
2619 .fo_write = badfo_readwrite,
2620 .fo_ioctl = badfo_ioctl,
2621 .fo_poll = badfo_poll,
2622 .fo_kqfilter = badfo_kqfilter,
2623 .fo_stat = badfo_stat,
2624 .fo_close = badfo_close,
2628 /*-------------------------------------------------------------------*/
2631 * File Descriptor pseudo-device driver (/dev/fd/).
2633 * Opening minor device N dup()s the file (if any) connected to file
2634 * descriptor N belonging to the calling process. Note that this driver
2635 * consists of only the ``open()'' routine, because all subsequent
2636 * references to this file will be direct to the other driver.
2638 * XXX: we could give this one a cloning event handler if necessary.
2643 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2647 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2648 * the file descriptor being sought for duplication. The error
2649 * return ensures that the vnode for this device will be released
2650 * by vn_open. Open will detect this special error and take the
2651 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2652 * will simply report the error.
2654 td->td_dupfd = dev2unit(dev);
2658 static struct cdevsw fildesc_cdevsw = {
2659 .d_version = D_VERSION,
2660 .d_flags = D_NEEDGIANT,
2666 fildesc_drvinit(void *unused)
2670 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2671 make_dev_alias(dev, "stdin");
2672 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2673 make_dev_alias(dev, "stdout");
2674 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2675 make_dev_alias(dev, "stderr");
2678 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)