2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_compat.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
47 #include <sys/fcntl.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mqueue.h>
58 #include <sys/mutex.h>
59 #include <sys/namei.h>
62 #include <sys/resourcevar.h>
63 #include <sys/signalvar.h>
64 #include <sys/socketvar.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/sysctl.h>
69 #include <sys/sysproto.h>
70 #include <sys/unistd.h>
71 #include <sys/vnode.h>
73 #include <security/audit/audit.h>
79 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
80 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
81 "file desc to leader structures");
82 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
84 static uma_zone_t file_zone;
87 /* How to treat 'new' parameter when allocating a fd for do_dup(). */
88 enum dup_type { DUP_VARIABLE, DUP_FIXED };
90 static int do_dup(struct thread *td, enum dup_type type, int old, int new,
92 static int fd_first_free(struct filedesc *, int, int);
93 static int fd_last_used(struct filedesc *, int, int);
94 static void fdgrowtable(struct filedesc *, int);
95 static int fdrop_locked(struct file *fp, struct thread *td);
96 static void fdunused(struct filedesc *fdp, int fd);
97 static void fdused(struct filedesc *fdp, int fd);
100 * A process is initially started out with NDFILE descriptors stored within
101 * this structure, selected to be enough for typical applications based on
102 * the historical limit of 20 open files (and the usage of descriptors by
103 * shells). If these descriptors are exhausted, a larger descriptor table
104 * may be allocated, up to a process' resource limit; the internal arrays
108 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
109 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
110 #define NDSLOT(x) ((x) / NDENTRIES)
111 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
112 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
115 * Storage required per open file descriptor.
117 #define OFILESIZE (sizeof(struct file *) + sizeof(char))
120 * Basic allocation of descriptors:
121 * one of the above, plus arrays for NDFILE descriptors.
124 struct filedesc fd_fd;
126 * These arrays are used when the number of open files is
127 * <= NDFILE, and are then pointed to by the pointers above.
129 struct file *fd_dfiles[NDFILE];
130 char fd_dfileflags[NDFILE];
131 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
135 * Descriptor management.
137 struct filelist filehead; /* head of list of open files */
138 int openfiles; /* actual number of open files */
139 struct sx filelist_lock; /* sx to protect filelist */
140 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
141 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
143 /* A mutex to protect the association between a proc and filedesc. */
144 static struct mtx fdesc_mtx;
147 * Find the first zero bit in the given bitmap, starting at low and not
148 * exceeding size - 1.
151 fd_first_free(struct filedesc *fdp, int low, int size)
153 NDSLOTTYPE *map = fdp->fd_map;
161 if (low % NDENTRIES) {
162 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
163 if ((mask &= ~map[off]) != 0UL)
164 return (off * NDENTRIES + ffsl(mask) - 1);
167 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
168 if (map[off] != ~0UL)
169 return (off * NDENTRIES + ffsl(~map[off]) - 1);
174 * Find the highest non-zero bit in the given bitmap, starting at low and
175 * not exceeding size - 1.
178 fd_last_used(struct filedesc *fdp, int low, int size)
180 NDSLOTTYPE *map = fdp->fd_map;
188 if (size % NDENTRIES) {
189 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
190 if ((mask &= map[off]) != 0)
191 return (off * NDENTRIES + flsl(mask) - 1);
194 for (minoff = NDSLOT(low); off >= minoff; --off)
196 return (off * NDENTRIES + flsl(map[off]) - 1);
201 fdisused(struct filedesc *fdp, int fd)
203 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
204 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
205 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
209 * Mark a file descriptor as used.
212 fdused(struct filedesc *fdp, int fd)
215 FILEDESC_XLOCK_ASSERT(fdp);
216 KASSERT(!fdisused(fdp, fd),
217 ("fd already used"));
219 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
220 if (fd > fdp->fd_lastfile)
221 fdp->fd_lastfile = fd;
222 if (fd == fdp->fd_freefile)
223 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
227 * Mark a file descriptor as unused.
230 fdunused(struct filedesc *fdp, int fd)
233 FILEDESC_XLOCK_ASSERT(fdp);
234 KASSERT(fdisused(fdp, fd),
235 ("fd is already unused"));
236 KASSERT(fdp->fd_ofiles[fd] == NULL,
237 ("fd is still in use"));
239 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
240 if (fd < fdp->fd_freefile)
241 fdp->fd_freefile = fd;
242 if (fd == fdp->fd_lastfile)
243 fdp->fd_lastfile = fd_last_used(fdp, 0, fd);
247 * System calls on descriptors.
249 #ifndef _SYS_SYSPROTO_H_
250 struct getdtablesize_args {
256 getdtablesize(struct thread *td, struct getdtablesize_args *uap)
258 struct proc *p = td->td_proc;
262 min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
268 * Duplicate a file descriptor to a particular value.
270 * Note: keep in mind that a potential race condition exists when closing
271 * descriptors from a shared descriptor table (via rfork).
273 #ifndef _SYS_SYSPROTO_H_
281 dup2(struct thread *td, struct dup2_args *uap)
284 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to,
289 * Duplicate a file descriptor.
291 #ifndef _SYS_SYSPROTO_H_
298 dup(struct thread *td, struct dup_args *uap)
301 return (do_dup(td, DUP_VARIABLE, (int)uap->fd, 0, td->td_retval));
305 * The file control system call.
307 #ifndef _SYS_SYSPROTO_H_
316 fcntl(struct thread *td, struct fcntl_args *uap)
327 error = copyin((void *)(intptr_t)uap->arg, &fl, sizeof(fl));
336 error = kern_fcntl(td, uap->fd, uap->cmd, arg);
339 if (uap->cmd == F_GETLK)
340 error = copyout(&fl, (void *)(intptr_t)uap->arg, sizeof(fl));
344 static inline struct file *
345 fdtofp(int fd, struct filedesc *fdp)
349 FILEDESC_LOCK_ASSERT(fdp);
350 if ((unsigned)fd >= fdp->fd_nfiles ||
351 (fp = fdp->fd_ofiles[fd]) == NULL)
357 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
359 struct filedesc *fdp;
378 if ((fp = fdtofp(fd, fdp)) == NULL) {
379 FILEDESC_SUNLOCK(fdp);
383 FILEDESC_SUNLOCK(fdp);
386 if (newmin >= lim_cur(p, RLIMIT_NOFILE) ||
387 newmin >= maxfilesperproc) {
393 error = do_dup(td, DUP_VARIABLE, fd, newmin, td->td_retval);
398 if ((fp = fdtofp(fd, fdp)) == NULL) {
399 FILEDESC_SUNLOCK(fdp);
403 pop = &fdp->fd_ofileflags[fd];
404 td->td_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
405 FILEDESC_SUNLOCK(fdp);
410 if ((fp = fdtofp(fd, fdp)) == NULL) {
411 FILEDESC_XUNLOCK(fdp);
415 pop = &fdp->fd_ofileflags[fd];
416 *pop = (*pop &~ UF_EXCLOSE) |
417 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
418 FILEDESC_XUNLOCK(fdp);
423 if ((fp = fdtofp(fd, fdp)) == NULL) {
424 FILEDESC_SUNLOCK(fdp);
429 td->td_retval[0] = OFLAGS(fp->f_flag);
431 FILEDESC_SUNLOCK(fdp);
436 if ((fp = fdtofp(fd, fdp)) == NULL) {
437 FILEDESC_SUNLOCK(fdp);
443 fp->f_flag &= ~FCNTLFLAGS;
444 fp->f_flag |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
446 FILEDESC_SUNLOCK(fdp);
447 tmp = fp->f_flag & FNONBLOCK;
448 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
453 tmp = fp->f_flag & FASYNC;
454 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
460 fp->f_flag &= ~FNONBLOCK;
463 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
469 if ((fp = fdtofp(fd, fdp)) == NULL) {
470 FILEDESC_SUNLOCK(fdp);
475 FILEDESC_SUNLOCK(fdp);
476 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
478 td->td_retval[0] = tmp;
484 if ((fp = fdtofp(fd, fdp)) == NULL) {
485 FILEDESC_SUNLOCK(fdp);
490 FILEDESC_SUNLOCK(fdp);
492 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
498 /* FALLTHROUGH F_SETLK */
502 if ((fp = fdtofp(fd, fdp)) == NULL) {
503 FILEDESC_SUNLOCK(fdp);
507 if (fp->f_type != DTYPE_VNODE) {
508 FILEDESC_SUNLOCK(fdp);
512 flp = (struct flock *)arg;
513 if (flp->l_whence == SEEK_CUR) {
514 if (fp->f_offset < 0 ||
516 fp->f_offset > OFF_MAX - flp->l_start)) {
517 FILEDESC_SUNLOCK(fdp);
521 flp->l_start += fp->f_offset;
525 * VOP_ADVLOCK() may block.
528 FILEDESC_SUNLOCK(fdp);
530 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
531 switch (flp->l_type) {
533 if ((fp->f_flag & FREAD) == 0) {
537 PROC_LOCK(p->p_leader);
538 p->p_leader->p_flag |= P_ADVLOCK;
539 PROC_UNLOCK(p->p_leader);
540 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
544 if ((fp->f_flag & FWRITE) == 0) {
548 PROC_LOCK(p->p_leader);
549 p->p_leader->p_flag |= P_ADVLOCK;
550 PROC_UNLOCK(p->p_leader);
551 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
555 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
562 VFS_UNLOCK_GIANT(vfslocked);
564 /* Check for race with close */
566 if ((unsigned) fd >= fdp->fd_nfiles ||
567 fp != fdp->fd_ofiles[fd]) {
568 FILEDESC_SUNLOCK(fdp);
569 flp->l_whence = SEEK_SET;
572 flp->l_type = F_UNLCK;
573 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
574 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
575 F_UNLCK, flp, F_POSIX);
576 VFS_UNLOCK_GIANT(vfslocked);
579 FILEDESC_SUNLOCK(fdp);
585 if ((fp = fdtofp(fd, fdp)) == NULL) {
586 FILEDESC_SUNLOCK(fdp);
590 if (fp->f_type != DTYPE_VNODE) {
591 FILEDESC_SUNLOCK(fdp);
595 flp = (struct flock *)arg;
596 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
597 flp->l_type != F_UNLCK) {
598 FILEDESC_SUNLOCK(fdp);
602 if (flp->l_whence == SEEK_CUR) {
603 if ((flp->l_start > 0 &&
604 fp->f_offset > OFF_MAX - flp->l_start) ||
606 fp->f_offset < OFF_MIN - flp->l_start)) {
607 FILEDESC_SUNLOCK(fdp);
611 flp->l_start += fp->f_offset;
614 * VOP_ADVLOCK() may block.
617 FILEDESC_SUNLOCK(fdp);
619 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
620 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
622 VFS_UNLOCK_GIANT(vfslocked);
630 VFS_UNLOCK_GIANT(vfslocked);
635 * Common code for dup, dup2, and fcntl(F_DUPFD).
638 do_dup(struct thread *td, enum dup_type type, int old, int new,
641 struct filedesc *fdp;
645 int error, holdleaders, maxfd;
647 KASSERT((type == DUP_VARIABLE || type == DUP_FIXED),
648 ("invalid dup type %d", type));
654 * Verify we have a valid descriptor to dup from and possibly to
657 if (old < 0 || new < 0)
660 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
666 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL) {
667 FILEDESC_XUNLOCK(fdp);
670 if (type == DUP_FIXED && old == new) {
672 FILEDESC_XUNLOCK(fdp);
675 fp = fdp->fd_ofiles[old];
679 * If the caller specified a file descriptor, make sure the file
680 * table is large enough to hold it, and grab it. Otherwise, just
681 * allocate a new descriptor the usual way. Since the filedesc
682 * lock may be temporarily dropped in the process, we have to look
685 if (type == DUP_FIXED) {
686 if (new >= fdp->fd_nfiles)
687 fdgrowtable(fdp, new + 1);
688 if (fdp->fd_ofiles[new] == NULL)
691 if ((error = fdalloc(td, new, &new)) != 0) {
692 FILEDESC_XUNLOCK(fdp);
699 * If the old file changed out from under us then treat it as a
700 * bad file descriptor. Userland should do its own locking to
703 if (fdp->fd_ofiles[old] != fp) {
704 /* we've allocated a descriptor which we won't use */
705 if (fdp->fd_ofiles[new] == NULL)
707 FILEDESC_XUNLOCK(fdp);
712 ("new fd is same as old"));
715 * Save info on the descriptor being overwritten. We cannot close
716 * it without introducing an ownership race for the slot, since we
717 * need to drop the filedesc lock to call closef().
719 * XXX this duplicates parts of close().
721 delfp = fdp->fd_ofiles[new];
724 if (td->td_proc->p_fdtol != NULL) {
726 * Ask fdfree() to sleep to ensure that all relevant
727 * process leaders can be traversed in closef().
729 fdp->fd_holdleaderscount++;
735 * Duplicate the source descriptor
737 fdp->fd_ofiles[new] = fp;
738 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
739 if (new > fdp->fd_lastfile)
740 fdp->fd_lastfile = new;
744 * If we dup'd over a valid file, we now own the reference to it
745 * and must dispose of it using closef() semantics (as if a
746 * close() were performed on it).
748 * XXX this duplicates parts of close().
751 knote_fdclose(td, new);
752 if (delfp->f_type == DTYPE_MQUEUE)
753 mq_fdclose(td, new, delfp);
754 FILEDESC_XUNLOCK(fdp);
755 (void) closef(delfp, td);
758 fdp->fd_holdleaderscount--;
759 if (fdp->fd_holdleaderscount == 0 &&
760 fdp->fd_holdleaderswakeup != 0) {
761 fdp->fd_holdleaderswakeup = 0;
762 wakeup(&fdp->fd_holdleaderscount);
764 FILEDESC_XUNLOCK(fdp);
767 FILEDESC_XUNLOCK(fdp);
773 * If sigio is on the list associated with a process or process group,
774 * disable signalling from the device, remove sigio from the list and
778 funsetown(struct sigio **sigiop)
788 *(sigio->sio_myref) = NULL;
789 if ((sigio)->sio_pgid < 0) {
790 struct pgrp *pg = (sigio)->sio_pgrp;
792 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
796 struct proc *p = (sigio)->sio_proc;
798 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
803 crfree(sigio->sio_ucred);
804 FREE(sigio, M_SIGIO);
808 * Free a list of sigio structures.
809 * We only need to lock the SIGIO_LOCK because we have made ourselves
810 * inaccessible to callers of fsetown and therefore do not need to lock
811 * the proc or pgrp struct for the list manipulation.
814 funsetownlst(struct sigiolst *sigiolst)
820 sigio = SLIST_FIRST(sigiolst);
827 * Every entry of the list should belong
828 * to a single proc or pgrp.
830 if (sigio->sio_pgid < 0) {
831 pg = sigio->sio_pgrp;
832 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
833 } else /* if (sigio->sio_pgid > 0) */ {
835 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
839 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
840 *(sigio->sio_myref) = NULL;
842 KASSERT(sigio->sio_pgid < 0,
843 ("Proc sigio in pgrp sigio list"));
844 KASSERT(sigio->sio_pgrp == pg,
845 ("Bogus pgrp in sigio list"));
847 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
850 } else /* if (p != NULL) */ {
851 KASSERT(sigio->sio_pgid > 0,
852 ("Pgrp sigio in proc sigio list"));
853 KASSERT(sigio->sio_proc == p,
854 ("Bogus proc in sigio list"));
856 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
861 crfree(sigio->sio_ucred);
862 FREE(sigio, M_SIGIO);
869 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
871 * After permission checking, add a sigio structure to the sigio list for
872 * the process or process group.
875 fsetown(pid_t pgid, struct sigio **sigiop)
889 /* Allocate and fill in the new sigio out of locks. */
890 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
891 sigio->sio_pgid = pgid;
892 sigio->sio_ucred = crhold(curthread->td_ucred);
893 sigio->sio_myref = sigiop;
895 sx_slock(&proctree_lock);
904 * Policy - Don't allow a process to FSETOWN a process
905 * in another session.
907 * Remove this test to allow maximum flexibility or
908 * restrict FSETOWN to the current process or process
909 * group for maximum safety.
912 if (proc->p_session != curthread->td_proc->p_session) {
918 } else /* if (pgid < 0) */ {
919 pgrp = pgfind(-pgid);
927 * Policy - Don't allow a process to FSETOWN a process
928 * in another session.
930 * Remove this test to allow maximum flexibility or
931 * restrict FSETOWN to the current process or process
932 * group for maximum safety.
934 if (pgrp->pg_session != curthread->td_proc->p_session) {
945 * Since funsetownlst() is called without the proctree
946 * locked, we need to check for P_WEXIT.
947 * XXX: is ESRCH correct?
949 if ((proc->p_flag & P_WEXIT) != 0) {
954 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
955 sigio->sio_proc = proc;
959 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
960 sigio->sio_pgrp = pgrp;
963 sx_sunlock(&proctree_lock);
970 sx_sunlock(&proctree_lock);
971 crfree(sigio->sio_ucred);
972 FREE(sigio, M_SIGIO);
977 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
981 struct sigio **sigiop;
986 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
992 * Close a file descriptor.
994 #ifndef _SYS_SYSPROTO_H_
1003 struct close_args *uap;
1006 return (kern_close(td, uap->fd));
1014 struct filedesc *fdp;
1021 fdp = td->td_proc->p_fd;
1023 AUDIT_SYSCLOSE(td, fd);
1025 FILEDESC_XLOCK(fdp);
1026 if ((unsigned)fd >= fdp->fd_nfiles ||
1027 (fp = fdp->fd_ofiles[fd]) == NULL) {
1028 FILEDESC_XUNLOCK(fdp);
1031 fdp->fd_ofiles[fd] = NULL;
1032 fdp->fd_ofileflags[fd] = 0;
1034 if (td->td_proc->p_fdtol != NULL) {
1036 * Ask fdfree() to sleep to ensure that all relevant
1037 * process leaders can be traversed in closef().
1039 fdp->fd_holdleaderscount++;
1044 * We now hold the fp reference that used to be owned by the
1045 * descriptor array. We have to unlock the FILEDESC *AFTER*
1046 * knote_fdclose to prevent a race of the fd getting opened, a knote
1047 * added, and deleteing a knote for the new fd.
1049 knote_fdclose(td, fd);
1050 if (fp->f_type == DTYPE_MQUEUE)
1051 mq_fdclose(td, fd, fp);
1052 FILEDESC_XUNLOCK(fdp);
1054 error = closef(fp, td);
1056 FILEDESC_XLOCK(fdp);
1057 fdp->fd_holdleaderscount--;
1058 if (fdp->fd_holdleaderscount == 0 &&
1059 fdp->fd_holdleaderswakeup != 0) {
1060 fdp->fd_holdleaderswakeup = 0;
1061 wakeup(&fdp->fd_holdleaderscount);
1063 FILEDESC_XUNLOCK(fdp);
1068 #if defined(COMPAT_43)
1070 * Return status information about a file descriptor.
1072 #ifndef _SYS_SYSPROTO_H_
1073 struct ofstat_args {
1080 ofstat(struct thread *td, struct ofstat_args *uap)
1086 error = kern_fstat(td, uap->fd, &ub);
1089 error = copyout(&oub, uap->sb, sizeof(oub));
1093 #endif /* COMPAT_43 */
1096 * Return status information about a file descriptor.
1098 #ifndef _SYS_SYSPROTO_H_
1106 fstat(struct thread *td, struct fstat_args *uap)
1111 error = kern_fstat(td, uap->fd, &ub);
1113 error = copyout(&ub, uap->sb, sizeof(ub));
1118 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1125 if ((error = fget(td, fd, &fp)) != 0)
1128 AUDIT_ARG(file, td->td_proc, fp);
1130 error = fo_stat(fp, sbp, td->td_ucred, td);
1136 * Return status information about a file descriptor.
1138 #ifndef _SYS_SYSPROTO_H_
1139 struct nfstat_args {
1146 nfstat(struct thread *td, struct nfstat_args *uap)
1152 error = kern_fstat(td, uap->fd, &ub);
1154 cvtnstat(&ub, &nub);
1155 error = copyout(&nub, uap->sb, sizeof(nub));
1161 * Return pathconf information about a file descriptor.
1163 #ifndef _SYS_SYSPROTO_H_
1164 struct fpathconf_args {
1171 fpathconf(struct thread *td, struct fpathconf_args *uap)
1177 if ((error = fget(td, uap->fd, &fp)) != 0)
1180 /* If asynchronous I/O is available, it works for all descriptors. */
1181 if (uap->name == _PC_ASYNC_IO) {
1182 td->td_retval[0] = async_io_version;
1188 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1189 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1190 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1191 VOP_UNLOCK(vp, 0, td);
1192 VFS_UNLOCK_GIANT(vfslocked);
1193 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1194 if (uap->name != _PC_PIPE_BUF) {
1197 td->td_retval[0] = PIPE_BUF;
1209 * Grow the file table to accomodate (at least) nfd descriptors. This may
1210 * block and drop the filedesc lock, but it will reacquire it before
1214 fdgrowtable(struct filedesc *fdp, int nfd)
1216 struct file **ntable;
1218 int nnfiles, onfiles;
1221 FILEDESC_XLOCK_ASSERT(fdp);
1223 KASSERT(fdp->fd_nfiles > 0,
1224 ("zero-length file table"));
1226 /* compute the size of the new table */
1227 onfiles = fdp->fd_nfiles;
1228 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1229 if (nnfiles <= onfiles)
1230 /* the table is already large enough */
1233 /* allocate a new table and (if required) new bitmaps */
1234 FILEDESC_XUNLOCK(fdp);
1235 MALLOC(ntable, struct file **, nnfiles * OFILESIZE,
1236 M_FILEDESC, M_ZERO | M_WAITOK);
1237 nfileflags = (char *)&ntable[nnfiles];
1238 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles))
1239 MALLOC(nmap, NDSLOTTYPE *, NDSLOTS(nnfiles) * NDSLOTSIZE,
1240 M_FILEDESC, M_ZERO | M_WAITOK);
1243 FILEDESC_XLOCK(fdp);
1246 * We now have new tables ready to go. Since we dropped the
1247 * filedesc lock to call malloc(), watch out for a race.
1249 onfiles = fdp->fd_nfiles;
1250 if (onfiles >= nnfiles) {
1251 /* we lost the race, but that's OK */
1252 free(ntable, M_FILEDESC);
1254 free(nmap, M_FILEDESC);
1257 bcopy(fdp->fd_ofiles, ntable, onfiles * sizeof(*ntable));
1258 bcopy(fdp->fd_ofileflags, nfileflags, onfiles);
1259 if (onfiles > NDFILE)
1260 free(fdp->fd_ofiles, M_FILEDESC);
1261 fdp->fd_ofiles = ntable;
1262 fdp->fd_ofileflags = nfileflags;
1263 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1264 bcopy(fdp->fd_map, nmap, NDSLOTS(onfiles) * sizeof(*nmap));
1265 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1266 free(fdp->fd_map, M_FILEDESC);
1269 fdp->fd_nfiles = nnfiles;
1273 * Allocate a file descriptor for the process.
1276 fdalloc(struct thread *td, int minfd, int *result)
1278 struct proc *p = td->td_proc;
1279 struct filedesc *fdp = p->p_fd;
1282 FILEDESC_XLOCK_ASSERT(fdp);
1284 if (fdp->fd_freefile > minfd)
1285 minfd = fdp->fd_freefile;
1288 maxfd = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1292 * Search the bitmap for a free descriptor. If none is found, try
1293 * to grow the file table. Keep at it until we either get a file
1294 * descriptor or run into process or system limits; fdgrowtable()
1295 * may drop the filedesc lock, so we're in a race.
1298 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1301 if (fd < fdp->fd_nfiles)
1303 fdgrowtable(fdp, min(fdp->fd_nfiles * 2, maxfd));
1307 * Perform some sanity checks, then mark the file descriptor as
1308 * used and return it to the caller.
1310 KASSERT(!fdisused(fdp, fd),
1311 ("fd_first_free() returned non-free descriptor"));
1312 KASSERT(fdp->fd_ofiles[fd] == NULL,
1313 ("free descriptor isn't"));
1314 fdp->fd_ofileflags[fd] = 0; /* XXX needed? */
1321 * Check to see whether n user file descriptors are available to the process
1325 fdavail(struct thread *td, int n)
1327 struct proc *p = td->td_proc;
1328 struct filedesc *fdp = td->td_proc->p_fd;
1332 FILEDESC_LOCK_ASSERT(fdp);
1335 lim = min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
1337 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1339 last = min(fdp->fd_nfiles, lim);
1340 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
1341 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
1342 if (*fpp == NULL && --n <= 0)
1349 * Create a new open file structure and allocate a file decriptor for the
1350 * process that refers to it. We add one reference to the file for the
1351 * descriptor table and one reference for resultfp. This is to prevent us
1352 * being preempted and the entry in the descriptor table closed after we
1353 * release the FILEDESC lock.
1356 falloc(struct thread *td, struct file **resultfp, int *resultfd)
1358 struct proc *p = td->td_proc;
1359 struct file *fp, *fq;
1361 int maxuserfiles = maxfiles - (maxfiles / 20);
1362 static struct timeval lastfail;
1365 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1366 sx_xlock(&filelist_lock);
1368 if ((openfiles >= maxuserfiles &&
1369 priv_check(td, PRIV_MAXFILES) != 0) ||
1370 openfiles >= maxfiles) {
1371 if (ppsratecheck(&lastfail, &curfail, 1)) {
1372 printf("kern.maxfiles limit exceeded by uid %i, please see tuning(7).\n",
1373 td->td_ucred->cr_ruid);
1375 sx_xunlock(&filelist_lock);
1376 uma_zfree(file_zone, fp);
1382 * If the process has file descriptor zero open, add the new file
1383 * descriptor to the list of open files at that point, otherwise
1384 * put it at the front of the list of open files.
1386 fp->f_mtxp = mtx_pool_alloc(mtxpool_sleep);
1390 fp->f_cred = crhold(td->td_ucred);
1391 fp->f_ops = &badfileops;
1394 FILEDESC_XLOCK(p->p_fd);
1395 if ((fq = p->p_fd->fd_ofiles[0])) {
1396 LIST_INSERT_AFTER(fq, fp, f_list);
1398 LIST_INSERT_HEAD(&filehead, fp, f_list);
1400 sx_xunlock(&filelist_lock);
1401 if ((error = fdalloc(td, 0, &i))) {
1402 FILEDESC_XUNLOCK(p->p_fd);
1408 p->p_fd->fd_ofiles[i] = fp;
1409 FILEDESC_XUNLOCK(p->p_fd);
1418 * Build a new filedesc structure from another.
1419 * Copy the current, root, and jail root vnode references.
1422 fdinit(struct filedesc *fdp)
1424 struct filedesc0 *newfdp;
1426 newfdp = malloc(sizeof *newfdp, M_FILEDESC, M_WAITOK | M_ZERO);
1427 FILEDESC_LOCK_INIT(&newfdp->fd_fd);
1429 FILEDESC_XLOCK(fdp);
1430 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1431 if (newfdp->fd_fd.fd_cdir)
1432 VREF(newfdp->fd_fd.fd_cdir);
1433 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1434 if (newfdp->fd_fd.fd_rdir)
1435 VREF(newfdp->fd_fd.fd_rdir);
1436 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1437 if (newfdp->fd_fd.fd_jdir)
1438 VREF(newfdp->fd_fd.fd_jdir);
1439 FILEDESC_XUNLOCK(fdp);
1442 /* Create the file descriptor table. */
1443 newfdp->fd_fd.fd_refcnt = 1;
1444 newfdp->fd_fd.fd_holdcnt = 1;
1445 newfdp->fd_fd.fd_cmask = CMASK;
1446 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1447 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1448 newfdp->fd_fd.fd_nfiles = NDFILE;
1449 newfdp->fd_fd.fd_map = newfdp->fd_dmap;
1450 newfdp->fd_fd.fd_lastfile = -1;
1451 return (&newfdp->fd_fd);
1454 static struct filedesc *
1455 fdhold(struct proc *p)
1457 struct filedesc *fdp;
1459 mtx_lock(&fdesc_mtx);
1463 mtx_unlock(&fdesc_mtx);
1468 fddrop(struct filedesc *fdp)
1472 mtx_lock(&fdesc_mtx);
1473 i = --fdp->fd_holdcnt;
1474 mtx_unlock(&fdesc_mtx);
1478 FILEDESC_LOCK_DESTROY(fdp);
1479 FREE(fdp, M_FILEDESC);
1483 * Share a filedesc structure.
1486 fdshare(struct filedesc *fdp)
1489 FILEDESC_XLOCK(fdp);
1491 FILEDESC_XUNLOCK(fdp);
1496 * Unshare a filedesc structure, if necessary by making a copy
1499 fdunshare(struct proc *p, struct thread *td)
1502 FILEDESC_XLOCK(p->p_fd);
1503 if (p->p_fd->fd_refcnt > 1) {
1504 struct filedesc *tmp;
1506 FILEDESC_XUNLOCK(p->p_fd);
1507 tmp = fdcopy(p->p_fd);
1511 FILEDESC_XUNLOCK(p->p_fd);
1515 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1516 * this is to ease callers, not catch errors.
1519 fdcopy(struct filedesc *fdp)
1521 struct filedesc *newfdp;
1524 /* Certain daemons might not have file descriptors. */
1528 newfdp = fdinit(fdp);
1529 FILEDESC_SLOCK(fdp);
1530 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1531 FILEDESC_SUNLOCK(fdp);
1532 FILEDESC_XLOCK(newfdp);
1533 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1534 FILEDESC_XUNLOCK(newfdp);
1535 FILEDESC_SLOCK(fdp);
1537 /* copy everything except kqueue descriptors */
1538 newfdp->fd_freefile = -1;
1539 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1540 if (fdisused(fdp, i) &&
1541 fdp->fd_ofiles[i]->f_type != DTYPE_KQUEUE) {
1542 newfdp->fd_ofiles[i] = fdp->fd_ofiles[i];
1543 newfdp->fd_ofileflags[i] = fdp->fd_ofileflags[i];
1544 fhold(newfdp->fd_ofiles[i]);
1545 newfdp->fd_lastfile = i;
1547 if (newfdp->fd_freefile == -1)
1548 newfdp->fd_freefile = i;
1551 FILEDESC_SUNLOCK(fdp);
1552 FILEDESC_XLOCK(newfdp);
1553 for (i = 0; i <= newfdp->fd_lastfile; ++i)
1554 if (newfdp->fd_ofiles[i] != NULL)
1556 FILEDESC_XUNLOCK(newfdp);
1557 FILEDESC_SLOCK(fdp);
1558 if (newfdp->fd_freefile == -1)
1559 newfdp->fd_freefile = i;
1560 newfdp->fd_cmask = fdp->fd_cmask;
1561 FILEDESC_SUNLOCK(fdp);
1566 * Release a filedesc structure.
1569 fdfree(struct thread *td)
1571 struct filedesc *fdp;
1574 struct filedesc_to_leader *fdtol;
1576 struct vnode *cdir, *jdir, *rdir, *vp;
1579 /* Certain daemons might not have file descriptors. */
1580 fdp = td->td_proc->p_fd;
1584 /* Check for special need to clear POSIX style locks */
1585 fdtol = td->td_proc->p_fdtol;
1586 if (fdtol != NULL) {
1587 FILEDESC_XLOCK(fdp);
1588 KASSERT(fdtol->fdl_refcount > 0,
1589 ("filedesc_to_refcount botch: fdl_refcount=%d",
1590 fdtol->fdl_refcount));
1591 if (fdtol->fdl_refcount == 1 &&
1592 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1593 for (i = 0, fpp = fdp->fd_ofiles;
1594 i <= fdp->fd_lastfile;
1597 (*fpp)->f_type != DTYPE_VNODE)
1601 FILEDESC_XUNLOCK(fdp);
1602 lf.l_whence = SEEK_SET;
1605 lf.l_type = F_UNLCK;
1607 locked = VFS_LOCK_GIANT(vp->v_mount);
1608 (void) VOP_ADVLOCK(vp,
1609 (caddr_t)td->td_proc->
1614 VFS_UNLOCK_GIANT(locked);
1615 FILEDESC_XLOCK(fdp);
1617 fpp = fdp->fd_ofiles + i;
1621 if (fdtol->fdl_refcount == 1) {
1622 if (fdp->fd_holdleaderscount > 0 &&
1623 (td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1625 * close() or do_dup() has cleared a reference
1626 * in a shared file descriptor table.
1628 fdp->fd_holdleaderswakeup = 1;
1629 sx_sleep(&fdp->fd_holdleaderscount,
1630 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1633 if (fdtol->fdl_holdcount > 0) {
1635 * Ensure that fdtol->fdl_leader remains
1636 * valid in closef().
1638 fdtol->fdl_wakeup = 1;
1639 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
1644 fdtol->fdl_refcount--;
1645 if (fdtol->fdl_refcount == 0 &&
1646 fdtol->fdl_holdcount == 0) {
1647 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1648 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1651 td->td_proc->p_fdtol = NULL;
1652 FILEDESC_XUNLOCK(fdp);
1654 FREE(fdtol, M_FILEDESC_TO_LEADER);
1656 FILEDESC_XLOCK(fdp);
1657 i = --fdp->fd_refcnt;
1658 FILEDESC_XUNLOCK(fdp);
1662 * We are the last reference to the structure, so we can
1663 * safely assume it will not change out from under us.
1665 fpp = fdp->fd_ofiles;
1666 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1668 (void) closef(*fpp, td);
1670 FILEDESC_XLOCK(fdp);
1672 /* XXX This should happen earlier. */
1673 mtx_lock(&fdesc_mtx);
1674 td->td_proc->p_fd = NULL;
1675 mtx_unlock(&fdesc_mtx);
1677 if (fdp->fd_nfiles > NDFILE)
1678 FREE(fdp->fd_ofiles, M_FILEDESC);
1679 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
1680 FREE(fdp->fd_map, M_FILEDESC);
1684 cdir = fdp->fd_cdir;
1685 fdp->fd_cdir = NULL;
1686 rdir = fdp->fd_rdir;
1687 fdp->fd_rdir = NULL;
1688 jdir = fdp->fd_jdir;
1689 fdp->fd_jdir = NULL;
1690 FILEDESC_XUNLOCK(fdp);
1693 locked = VFS_LOCK_GIANT(cdir->v_mount);
1695 VFS_UNLOCK_GIANT(locked);
1698 locked = VFS_LOCK_GIANT(rdir->v_mount);
1700 VFS_UNLOCK_GIANT(locked);
1703 locked = VFS_LOCK_GIANT(jdir->v_mount);
1705 VFS_UNLOCK_GIANT(locked);
1712 * For setugid programs, we don't want to people to use that setugidness
1713 * to generate error messages which write to a file which otherwise would
1714 * otherwise be off-limits to the process. We check for filesystems where
1715 * the vnode can change out from under us after execve (like [lin]procfs).
1717 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1718 * sufficient. We also don't check for setugidness since we know we are.
1721 is_unsafe(struct file *fp)
1723 if (fp->f_type == DTYPE_VNODE) {
1724 struct vnode *vp = fp->f_vnode;
1726 if ((vp->v_vflag & VV_PROCDEP) != 0)
1733 * Make this setguid thing safe, if at all possible.
1736 setugidsafety(struct thread *td)
1738 struct filedesc *fdp;
1741 /* Certain daemons might not have file descriptors. */
1742 fdp = td->td_proc->p_fd;
1747 * Note: fdp->fd_ofiles may be reallocated out from under us while
1748 * we are blocked in a close. Be careful!
1750 FILEDESC_XLOCK(fdp);
1751 for (i = 0; i <= fdp->fd_lastfile; i++) {
1754 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1757 knote_fdclose(td, i);
1759 * NULL-out descriptor prior to close to avoid
1760 * a race while close blocks.
1762 fp = fdp->fd_ofiles[i];
1763 fdp->fd_ofiles[i] = NULL;
1764 fdp->fd_ofileflags[i] = 0;
1766 FILEDESC_XUNLOCK(fdp);
1767 (void) closef(fp, td);
1768 FILEDESC_XLOCK(fdp);
1771 FILEDESC_XUNLOCK(fdp);
1775 * If a specific file object occupies a specific file descriptor, close the
1776 * file descriptor entry and drop a reference on the file object. This is a
1777 * convenience function to handle a subsequent error in a function that calls
1778 * falloc() that handles the race that another thread might have closed the
1779 * file descriptor out from under the thread creating the file object.
1782 fdclose(struct filedesc *fdp, struct file *fp, int idx, struct thread *td)
1785 FILEDESC_XLOCK(fdp);
1786 if (fdp->fd_ofiles[idx] == fp) {
1787 fdp->fd_ofiles[idx] = NULL;
1789 FILEDESC_XUNLOCK(fdp);
1792 FILEDESC_XUNLOCK(fdp);
1796 * Close any files on exec?
1799 fdcloseexec(struct thread *td)
1801 struct filedesc *fdp;
1804 /* Certain daemons might not have file descriptors. */
1805 fdp = td->td_proc->p_fd;
1809 FILEDESC_XLOCK(fdp);
1812 * We cannot cache fd_ofiles or fd_ofileflags since operations
1813 * may block and rip them out from under us.
1815 for (i = 0; i <= fdp->fd_lastfile; i++) {
1816 if (fdp->fd_ofiles[i] != NULL &&
1817 (fdp->fd_ofiles[i]->f_type == DTYPE_MQUEUE ||
1818 (fdp->fd_ofileflags[i] & UF_EXCLOSE))) {
1821 knote_fdclose(td, i);
1823 * NULL-out descriptor prior to close to avoid
1824 * a race while close blocks.
1826 fp = fdp->fd_ofiles[i];
1827 fdp->fd_ofiles[i] = NULL;
1828 fdp->fd_ofileflags[i] = 0;
1830 if (fp->f_type == DTYPE_MQUEUE)
1831 mq_fdclose(td, i, fp);
1832 FILEDESC_XUNLOCK(fdp);
1833 (void) closef(fp, td);
1834 FILEDESC_XLOCK(fdp);
1837 FILEDESC_XUNLOCK(fdp);
1841 * It is unsafe for set[ug]id processes to be started with file
1842 * descriptors 0..2 closed, as these descriptors are given implicit
1843 * significance in the Standard C library. fdcheckstd() will create a
1844 * descriptor referencing /dev/null for each of stdin, stdout, and
1845 * stderr that is not already open.
1848 fdcheckstd(struct thread *td)
1850 struct filedesc *fdp;
1851 register_t retval, save;
1852 int i, error, devnull;
1854 fdp = td->td_proc->p_fd;
1857 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
1860 for (i = 0; i < 3; i++) {
1861 if (fdp->fd_ofiles[i] != NULL)
1864 save = td->td_retval[0];
1865 error = kern_open(td, "/dev/null", UIO_SYSSPACE,
1867 devnull = td->td_retval[0];
1868 KASSERT(devnull == i, ("oof, we didn't get our fd"));
1869 td->td_retval[0] = save;
1873 error = do_dup(td, DUP_FIXED, devnull, i, &retval);
1882 * Internal form of close. Decrement reference count on file structure.
1883 * Note: td may be NULL when closing a file that was being passed in a
1886 * XXXRW: Giant is not required for the caller, but often will be held; this
1887 * makes it moderately likely the Giant will be recursed in the VFS case.
1890 closef(struct file *fp, struct thread *td)
1894 struct filedesc_to_leader *fdtol;
1895 struct filedesc *fdp;
1898 * POSIX record locking dictates that any close releases ALL
1899 * locks owned by this process. This is handled by setting
1900 * a flag in the unlock to free ONLY locks obeying POSIX
1901 * semantics, and not to free BSD-style file locks.
1902 * If the descriptor was in a message, POSIX-style locks
1903 * aren't passed with the descriptor, and the thread pointer
1904 * will be NULL. Callers should be careful only to pass a
1905 * NULL thread pointer when there really is no owning
1906 * context that might have locks, or the locks will be
1909 if (fp->f_type == DTYPE_VNODE && td != NULL) {
1913 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1914 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
1915 lf.l_whence = SEEK_SET;
1918 lf.l_type = F_UNLCK;
1919 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
1920 F_UNLCK, &lf, F_POSIX);
1922 fdtol = td->td_proc->p_fdtol;
1923 if (fdtol != NULL) {
1925 * Handle special case where file descriptor table is
1926 * shared between multiple process leaders.
1928 fdp = td->td_proc->p_fd;
1929 FILEDESC_XLOCK(fdp);
1930 for (fdtol = fdtol->fdl_next;
1931 fdtol != td->td_proc->p_fdtol;
1932 fdtol = fdtol->fdl_next) {
1933 if ((fdtol->fdl_leader->p_flag &
1936 fdtol->fdl_holdcount++;
1937 FILEDESC_XUNLOCK(fdp);
1938 lf.l_whence = SEEK_SET;
1941 lf.l_type = F_UNLCK;
1943 (void) VOP_ADVLOCK(vp,
1944 (caddr_t)fdtol->fdl_leader,
1945 F_UNLCK, &lf, F_POSIX);
1946 FILEDESC_XLOCK(fdp);
1947 fdtol->fdl_holdcount--;
1948 if (fdtol->fdl_holdcount == 0 &&
1949 fdtol->fdl_wakeup != 0) {
1950 fdtol->fdl_wakeup = 0;
1954 FILEDESC_XUNLOCK(fdp);
1956 VFS_UNLOCK_GIANT(vfslocked);
1958 return (fdrop(fp, td));
1962 * Extract the file pointer associated with the specified descriptor for the
1963 * current user process.
1965 * If the descriptor doesn't exist, EBADF is returned.
1967 * If the descriptor exists but doesn't match 'flags' then return EBADF for
1968 * read attempts and EINVAL for write attempts.
1970 * If 'hold' is set (non-zero) the file's refcount will be bumped on return.
1971 * It should be dropped with fdrop(). If it is not set, then the refcount
1972 * will not be bumped however the thread's filedesc struct will be returned
1973 * locked (for fgetsock).
1975 * If an error occured the non-zero error is returned and *fpp is set to
1976 * NULL. Otherwise *fpp is set and zero is returned.
1979 _fget(struct thread *td, int fd, struct file **fpp, int flags, int hold)
1981 struct filedesc *fdp;
1985 if (td == NULL || (fdp = td->td_proc->p_fd) == NULL)
1987 FILEDESC_SLOCK(fdp);
1988 if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1989 FILEDESC_SUNLOCK(fdp);
1994 * FREAD and FWRITE failure return EBADF as per POSIX.
1996 * Only one flag, or 0, may be specified.
1998 if (flags == FREAD && (fp->f_flag & FREAD) == 0) {
1999 FILEDESC_SUNLOCK(fdp);
2002 if (flags == FWRITE && (fp->f_flag & FWRITE) == 0) {
2003 FILEDESC_SUNLOCK(fdp);
2008 FILEDESC_SUNLOCK(fdp);
2015 fget(struct thread *td, int fd, struct file **fpp)
2018 return(_fget(td, fd, fpp, 0, 1));
2022 fget_read(struct thread *td, int fd, struct file **fpp)
2025 return(_fget(td, fd, fpp, FREAD, 1));
2029 fget_write(struct thread *td, int fd, struct file **fpp)
2032 return(_fget(td, fd, fpp, FWRITE, 1));
2036 * Like fget() but loads the underlying vnode, or returns an error if the
2037 * descriptor does not represent a vnode. Note that pipes use vnodes but
2038 * never have VM objects. The returned vnode will be vref()'d.
2040 * XXX: what about the unused flags ?
2043 _fgetvp(struct thread *td, int fd, struct vnode **vpp, int flags)
2049 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2051 if (fp->f_vnode == NULL) {
2057 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2062 fgetvp(struct thread *td, int fd, struct vnode **vpp)
2065 return (_fgetvp(td, fd, vpp, 0));
2069 fgetvp_read(struct thread *td, int fd, struct vnode **vpp)
2072 return (_fgetvp(td, fd, vpp, FREAD));
2077 fgetvp_write(struct thread *td, int fd, struct vnode **vpp)
2080 return (_fgetvp(td, fd, vpp, FWRITE));
2085 * Like fget() but loads the underlying socket, or returns an error if the
2086 * descriptor does not represent a socket.
2088 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2091 * XXXRW: fgetsock() and fputsock() are deprecated, as consumers should rely
2092 * on their file descriptor reference to prevent the socket from being free'd
2096 fgetsock(struct thread *td, int fd, struct socket **spp, u_int *fflagp)
2104 if ((error = _fget(td, fd, &fp, 0, 0)) != 0)
2106 if (fp->f_type != DTYPE_SOCKET) {
2111 *fflagp = fp->f_flag;
2116 FILEDESC_SUNLOCK(td->td_proc->p_fd);
2121 * Drop the reference count on the socket and XXX release the SX lock in the
2122 * future. The last reference closes the socket.
2124 * XXXRW: fputsock() is deprecated, see comment for fgetsock().
2127 fputsock(struct socket *so)
2136 fdrop(struct file *fp, struct thread *td)
2140 return (fdrop_locked(fp, td));
2144 * Drop reference on struct file passed in, may call closef if the
2145 * reference hits zero.
2146 * Expects struct file locked, and will unlock it.
2149 fdrop_locked(struct file *fp, struct thread *td)
2153 FILE_LOCK_ASSERT(fp, MA_OWNED);
2155 if (--fp->f_count > 0) {
2161 * We might have just dropped the last reference to a file
2162 * object that is for a UNIX domain socket whose message
2163 * buffers are being examined in unp_gc(). If that is the
2164 * case, FWAIT will be set in f_gcflag and we need to wait for
2165 * unp_gc() to finish its scan.
2167 while (fp->f_gcflag & FWAIT)
2168 msleep(&fp->f_gcflag, fp->f_mtxp, 0, "fpdrop", 0);
2170 /* We have the last ref so we can proceed without the file lock. */
2172 if (fp->f_count < 0)
2173 panic("fdrop: count < 0");
2174 if (fp->f_ops != &badfileops)
2175 error = fo_close(fp, td);
2179 sx_xlock(&filelist_lock);
2180 LIST_REMOVE(fp, f_list);
2182 sx_xunlock(&filelist_lock);
2184 uma_zfree(file_zone, fp);
2190 * Apply an advisory lock on a file descriptor.
2192 * Just attempt to get a record lock of the requested type on the entire file
2193 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2195 #ifndef _SYS_SYSPROTO_H_
2203 flock(struct thread *td, struct flock_args *uap)
2211 if ((error = fget(td, uap->fd, &fp)) != 0)
2213 if (fp->f_type != DTYPE_VNODE) {
2215 return (EOPNOTSUPP);
2219 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
2220 lf.l_whence = SEEK_SET;
2223 if (uap->how & LOCK_UN) {
2224 lf.l_type = F_UNLCK;
2226 fp->f_flag &= ~FHASLOCK;
2228 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2231 if (uap->how & LOCK_EX)
2232 lf.l_type = F_WRLCK;
2233 else if (uap->how & LOCK_SH)
2234 lf.l_type = F_RDLCK;
2240 fp->f_flag |= FHASLOCK;
2242 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2243 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2246 VFS_UNLOCK_GIANT(vfslocked);
2250 * Duplicate the specified descriptor to a free descriptor.
2253 dupfdopen(struct thread *td, struct filedesc *fdp, int indx, int dfd, int mode, int error)
2259 * If the to-be-dup'd fd number is greater than the allowed number
2260 * of file descriptors, or the fd to be dup'd has already been
2261 * closed, then reject.
2263 FILEDESC_XLOCK(fdp);
2264 if (dfd < 0 || dfd >= fdp->fd_nfiles ||
2265 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
2266 FILEDESC_XUNLOCK(fdp);
2271 * There are two cases of interest here.
2273 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2275 * For ENXIO steal away the file structure from (dfd) and store it in
2276 * (indx). (dfd) is effectively closed by this operation.
2278 * Any other error code is just returned.
2283 * Check that the mode the file is being opened for is a
2284 * subset of the mode of the existing descriptor.
2287 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
2289 FILEDESC_XUNLOCK(fdp);
2292 fp = fdp->fd_ofiles[indx];
2293 fdp->fd_ofiles[indx] = wfp;
2294 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2299 FILEDESC_XUNLOCK(fdp);
2302 * We now own the reference to fp that the ofiles[]
2303 * array used to own. Release it.
2310 * Steal away the file pointer from dfd and stuff it into indx.
2312 fp = fdp->fd_ofiles[indx];
2313 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
2314 fdp->fd_ofiles[dfd] = NULL;
2315 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
2316 fdp->fd_ofileflags[dfd] = 0;
2320 FILEDESC_XUNLOCK(fdp);
2323 * We now own the reference to fp that the ofiles[] array
2324 * used to own. Release it.
2331 FILEDESC_XUNLOCK(fdp);
2338 * Scan all active processes to see if any of them have a current or root
2339 * directory of `olddp'. If so, replace them with the new mount point.
2342 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2344 struct filedesc *fdp;
2348 if (vrefcnt(olddp) == 1)
2350 sx_slock(&allproc_lock);
2351 FOREACH_PROC_IN_SYSTEM(p) {
2356 FILEDESC_XLOCK(fdp);
2357 if (fdp->fd_cdir == olddp) {
2359 fdp->fd_cdir = newdp;
2362 if (fdp->fd_rdir == olddp) {
2364 fdp->fd_rdir = newdp;
2367 FILEDESC_XUNLOCK(fdp);
2372 sx_sunlock(&allproc_lock);
2373 if (rootvnode == olddp) {
2380 struct filedesc_to_leader *
2381 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2383 struct filedesc_to_leader *fdtol;
2385 MALLOC(fdtol, struct filedesc_to_leader *,
2386 sizeof(struct filedesc_to_leader),
2387 M_FILEDESC_TO_LEADER,
2389 fdtol->fdl_refcount = 1;
2390 fdtol->fdl_holdcount = 0;
2391 fdtol->fdl_wakeup = 0;
2392 fdtol->fdl_leader = leader;
2394 FILEDESC_XLOCK(fdp);
2395 fdtol->fdl_next = old->fdl_next;
2396 fdtol->fdl_prev = old;
2397 old->fdl_next = fdtol;
2398 fdtol->fdl_next->fdl_prev = fdtol;
2399 FILEDESC_XUNLOCK(fdp);
2401 fdtol->fdl_next = fdtol;
2402 fdtol->fdl_prev = fdtol;
2408 * Get file structures.
2411 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2414 struct filedesc *fdp;
2420 * Note: because the number of file descriptors is calculated
2421 * in different ways for sizing vs returning the data,
2422 * there is information leakage from the first loop. However,
2423 * it is of a similar order of magnitude to the leakage from
2424 * global system statistics such as kern.openfiles.
2426 error = sysctl_wire_old_buffer(req, 0);
2429 if (req->oldptr == NULL) {
2430 n = 16; /* A slight overestimate. */
2431 sx_slock(&filelist_lock);
2432 LIST_FOREACH(fp, &filehead, f_list) {
2434 * We should grab the lock, but this is an
2435 * estimate, so does it really matter?
2437 /* mtx_lock(fp->f_mtxp); */
2439 /* mtx_unlock(f->f_mtxp); */
2441 sx_sunlock(&filelist_lock);
2442 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2445 bzero(&xf, sizeof(xf));
2446 xf.xf_size = sizeof(xf);
2447 sx_slock(&allproc_lock);
2448 FOREACH_PROC_IN_SYSTEM(p) {
2449 if (p->p_state == PRS_NEW)
2452 if (p_cansee(req->td, p) != 0) {
2456 xf.xf_pid = p->p_pid;
2457 xf.xf_uid = p->p_ucred->cr_uid;
2462 FILEDESC_SLOCK(fdp);
2463 for (n = 0; fdp->fd_refcnt > 0 && n < fdp->fd_nfiles; ++n) {
2464 if ((fp = fdp->fd_ofiles[n]) == NULL)
2468 xf.xf_data = fp->f_data;
2469 xf.xf_vnode = fp->f_vnode;
2470 xf.xf_type = fp->f_type;
2471 xf.xf_count = fp->f_count;
2472 xf.xf_msgcount = fp->f_msgcount;
2473 xf.xf_offset = fp->f_offset;
2474 xf.xf_flag = fp->f_flag;
2475 error = SYSCTL_OUT(req, &xf, sizeof(xf));
2479 FILEDESC_SUNLOCK(fdp);
2484 sx_sunlock(&allproc_lock);
2488 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2489 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
2493 * For the purposes of debugging, generate a human-readable string for the
2497 file_type_to_name(short type)
2523 * For the purposes of debugging, identify a process (if any, perhaps one of
2524 * many) that references the passed file in its file descriptor array. Return
2527 static struct proc *
2528 file_to_first_proc(struct file *fp)
2530 struct filedesc *fdp;
2534 FOREACH_PROC_IN_SYSTEM(p) {
2535 if (p->p_state == PRS_NEW)
2540 for (n = 0; n < fdp->fd_nfiles; n++) {
2541 if (fp == fdp->fd_ofiles[n])
2549 db_print_file(struct file *fp, int header)
2554 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
2555 "File", "Type", "Data", "Flag", "GCFl", "Count",
2556 "MCount", "Vnode", "FPID", "FCmd");
2557 p = file_to_first_proc(fp);
2558 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
2559 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
2560 fp->f_gcflag, fp->f_count, fp->f_msgcount, fp->f_vnode,
2561 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
2564 DB_SHOW_COMMAND(file, db_show_file)
2569 db_printf("usage: show file <addr>\n");
2572 fp = (struct file *)addr;
2573 db_print_file(fp, 1);
2576 DB_SHOW_COMMAND(files, db_show_files)
2582 LIST_FOREACH(fp, &filehead, f_list) {
2583 db_print_file(fp, header);
2589 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2590 &maxfilesperproc, 0, "Maximum files allowed open per process");
2592 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2593 &maxfiles, 0, "Maximum number of files");
2595 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2596 &openfiles, 0, "System-wide number of open files");
2600 filelistinit(void *dummy)
2603 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
2604 NULL, NULL, UMA_ALIGN_PTR, 0);
2605 sx_init(&filelist_lock, "filelist lock");
2606 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
2607 mtx_init(&fdesc_mtx, "fdesc", NULL, MTX_DEF);
2609 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL)
2611 /*-------------------------------------------------------------------*/
2614 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags, struct thread *td)
2621 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, struct thread *td)
2628 badfo_poll(struct file *fp, int events, struct ucred *active_cred, struct thread *td)
2635 badfo_kqfilter(struct file *fp, struct knote *kn)
2642 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, struct thread *td)
2649 badfo_close(struct file *fp, struct thread *td)
2655 struct fileops badfileops = {
2656 .fo_read = badfo_readwrite,
2657 .fo_write = badfo_readwrite,
2658 .fo_ioctl = badfo_ioctl,
2659 .fo_poll = badfo_poll,
2660 .fo_kqfilter = badfo_kqfilter,
2661 .fo_stat = badfo_stat,
2662 .fo_close = badfo_close,
2666 /*-------------------------------------------------------------------*/
2669 * File Descriptor pseudo-device driver (/dev/fd/).
2671 * Opening minor device N dup()s the file (if any) connected to file
2672 * descriptor N belonging to the calling process. Note that this driver
2673 * consists of only the ``open()'' routine, because all subsequent
2674 * references to this file will be direct to the other driver.
2676 * XXX: we could give this one a cloning event handler if necessary.
2681 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
2685 * XXX Kludge: set curthread->td_dupfd to contain the value of the
2686 * the file descriptor being sought for duplication. The error
2687 * return ensures that the vnode for this device will be released
2688 * by vn_open. Open will detect this special error and take the
2689 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2690 * will simply report the error.
2692 td->td_dupfd = dev2unit(dev);
2696 static struct cdevsw fildesc_cdevsw = {
2697 .d_version = D_VERSION,
2698 .d_flags = D_NEEDGIANT,
2704 fildesc_drvinit(void *unused)
2708 dev = make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "fd/0");
2709 make_dev_alias(dev, "stdin");
2710 dev = make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "fd/1");
2711 make_dev_alias(dev, "stdout");
2712 dev = make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "fd/2");
2713 make_dev_alias(dev, "stderr");
2716 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL)