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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
39 * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.17 2003/06/06 20:21:32 tegge Exp $
42 #include "opt_compat.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/sysproto.h>
48 #include <sys/filedesc.h>
49 #include <sys/kernel.h>
50 #include <sys/sysctl.h>
51 #include <sys/vnode.h>
53 #include <sys/namei.h>
56 #include <sys/filio.h>
57 #include <sys/fcntl.h>
58 #include <sys/unistd.h>
59 #include <sys/resourcevar.h>
60 #include <sys/event.h>
63 #include <vm/vm_extern.h>
65 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
66 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
67 "file desc to leader structures");
68 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
69 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
71 static d_open_t fdopen;
75 static struct cdevsw fildesc_cdevsw = {
83 /* strategy */ nostrategy,
92 static int do_dup __P((struct filedesc *fdp, int old, int new, register_t *retval, struct proc *p));
93 static int badfo_readwrite __P((struct file *fp, struct uio *uio,
94 struct ucred *cred, int flags, struct proc *p));
95 static int badfo_ioctl __P((struct file *fp, u_long com, caddr_t data,
97 static int badfo_poll __P((struct file *fp, int events,
98 struct ucred *cred, struct proc *p));
99 static int badfo_kqfilter __P((struct file *fp, struct knote *kn));
100 static int badfo_stat __P((struct file *fp, struct stat *sb, struct proc *p));
101 static int badfo_close __P((struct file *fp, struct proc *p));
104 * Descriptor management.
106 struct filelist filehead; /* head of list of open files */
107 int nfiles; /* actual number of open files */
111 * System calls on descriptors.
113 #ifndef _SYS_SYSPROTO_H_
114 struct getdtablesize_args {
120 getdtablesize(p, uap)
122 struct getdtablesize_args *uap;
126 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
131 * Duplicate a file descriptor to a particular value.
133 * note: keep in mind that a potential race condition exists when closing
134 * descriptors from a shared descriptor table (via rfork).
136 #ifndef _SYS_SYSPROTO_H_
146 struct dup2_args *uap;
148 register struct filedesc *fdp = p->p_fd;
149 register u_int old = uap->from, new = uap->to;
153 if (old >= fdp->fd_nfiles ||
154 fdp->fd_ofiles[old] == NULL ||
155 new >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
156 new >= maxfilesperproc) {
160 p->p_retval[0] = new;
163 if (new >= fdp->fd_nfiles) {
164 if ((error = fdalloc(p, new, &i)))
167 * fdalloc() may block, retest everything.
171 return (do_dup(fdp, (int)old, (int)new, p->p_retval, p));
175 * Duplicate a file descriptor.
177 #ifndef _SYS_SYSPROTO_H_
186 struct dup_args *uap;
188 register struct filedesc *fdp;
194 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
196 if ((error = fdalloc(p, 0, &new)))
198 return (do_dup(fdp, (int)old, new, p->p_retval, p));
202 * The file control system call.
204 #ifndef _SYS_SYSPROTO_H_
215 register struct fcntl_args *uap;
217 register struct filedesc *fdp = p->p_fd;
218 register struct file *fp;
221 int i, tmp, error, flg = F_POSIX;
225 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
226 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
228 pop = &fdp->fd_ofileflags[uap->fd];
233 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
234 newmin >= maxfilesperproc)
236 if ((error = fdalloc(p, newmin, &i)))
238 return (do_dup(fdp, uap->fd, i, p->p_retval, p));
241 p->p_retval[0] = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
245 *pop = (*pop &~ UF_EXCLOSE) |
246 (uap->arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
250 p->p_retval[0] = OFLAGS(fp->f_flag);
255 fp->f_flag &= ~FCNTLFLAGS;
256 fp->f_flag |= FFLAGS(uap->arg & ~O_ACCMODE) & FCNTLFLAGS;
257 tmp = fp->f_flag & FNONBLOCK;
258 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, p);
263 tmp = fp->f_flag & FASYNC;
264 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, p);
269 fp->f_flag &= ~FNONBLOCK;
271 (void)fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, p);
277 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)p->p_retval, p);
283 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&uap->arg, p);
289 /* Fall into F_SETLK */
292 if (fp->f_type != DTYPE_VNODE)
294 vp = (struct vnode *)fp->f_data;
297 * copyin/lockop may block
300 /* Copy in the lock structure */
301 error = copyin((caddr_t)(intptr_t)uap->arg, (caddr_t)&fl,
307 if (fl.l_whence == SEEK_CUR)
308 fl.l_start += fp->f_offset;
312 if ((fp->f_flag & FREAD) == 0) {
316 p->p_leader->p_flag |= P_ADVLOCK;
317 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
321 if ((fp->f_flag & FWRITE) == 0) {
325 p->p_leader->p_flag |= P_ADVLOCK;
326 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
330 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
337 /* Check for race with close */
338 if ((unsigned) uap->fd >= fdp->fd_nfiles ||
339 fp != fdp->fd_ofiles[uap->fd]) {
340 fl.l_whence = SEEK_SET;
344 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
345 F_UNLCK, &fl, F_POSIX);
351 if (fp->f_type != DTYPE_VNODE)
353 vp = (struct vnode *)fp->f_data;
355 * copyin/lockop may block
358 /* Copy in the lock structure */
359 error = copyin((caddr_t)(intptr_t)uap->arg, (caddr_t)&fl,
365 if (fl.l_type != F_RDLCK && fl.l_type != F_WRLCK &&
366 fl.l_type != F_UNLCK) {
370 if (fl.l_whence == SEEK_CUR)
371 fl.l_start += fp->f_offset;
372 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
376 error = copyout((caddr_t)&fl,
377 (caddr_t)(intptr_t)uap->arg, sizeof(fl));
387 * Common code for dup, dup2, and fcntl(F_DUPFD).
390 do_dup(fdp, old, new, retval, p)
391 register struct filedesc *fdp;
392 register int old, new;
401 * Save info on the descriptor being overwritten. We have
402 * to do the unmap now, but we cannot close it without
403 * introducing an ownership race for the slot.
405 delfp = fdp->fd_ofiles[new];
406 if (delfp != NULL && p->p_fdtol != NULL) {
408 * Ask fdfree() to sleep to ensure that all relevant
409 * process leaders can be traversed in closef().
411 fdp->fd_holdleaderscount++;
416 if (delfp && (fdp->fd_ofileflags[new] & UF_MAPPED))
417 (void) munmapfd(p, new);
421 * Duplicate the source descriptor, update lastfile
423 fp = fdp->fd_ofiles[old];
424 fdp->fd_ofiles[new] = fp;
425 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
427 if (new > fdp->fd_lastfile)
428 fdp->fd_lastfile = new;
432 * If we dup'd over a valid file, we now own the reference to it
433 * and must dispose of it using closef() semantics (as if a
434 * close() were performed on it).
437 (void) closef(delfp, p);
439 fdp->fd_holdleaderscount--;
440 if (fdp->fd_holdleaderscount == 0 &&
441 fdp->fd_holdleaderswakeup != 0) {
442 fdp->fd_holdleaderswakeup = 0;
443 wakeup(&fdp->fd_holdleaderscount);
451 * If sigio is on the list associated with a process or process group,
452 * disable signalling from the device, remove sigio from the list and
464 *(sigio->sio_myref) = NULL;
466 if (sigio->sio_pgid < 0) {
467 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
469 } else /* if ((*sigiop)->sio_pgid > 0) */ {
470 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
473 crfree(sigio->sio_ucred);
474 FREE(sigio, M_SIGIO);
477 /* Free a list of sigio structures. */
479 funsetownlst(sigiolst)
480 struct sigiolst *sigiolst;
484 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
489 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
491 * After permission checking, add a sigio structure to the sigio list for
492 * the process or process group.
495 fsetown(pgid, sigiop)
497 struct sigio **sigiop;
514 * Policy - Don't allow a process to FSETOWN a process
515 * in another session.
517 * Remove this test to allow maximum flexibility or
518 * restrict FSETOWN to the current process or process
519 * group for maximum safety.
521 if (proc->p_session != curproc->p_session)
525 } else /* if (pgid < 0) */ {
526 pgrp = pgfind(-pgid);
531 * Policy - Don't allow a process to FSETOWN a process
532 * in another session.
534 * Remove this test to allow maximum flexibility or
535 * restrict FSETOWN to the current process or process
536 * group for maximum safety.
538 if (pgrp->pg_session != curproc->p_session)
544 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
546 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
547 sigio->sio_proc = proc;
549 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
550 sigio->sio_pgrp = pgrp;
552 sigio->sio_pgid = pgid;
553 crhold(curproc->p_ucred);
554 sigio->sio_ucred = curproc->p_ucred;
555 /* It would be convenient if p_ruid was in ucred. */
556 sigio->sio_ruid = curproc->p_cred->p_ruid;
557 sigio->sio_myref = sigiop;
565 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
571 return (sigio != NULL ? sigio->sio_pgid : 0);
575 * Close a file descriptor.
577 #ifndef _SYS_SYSPROTO_H_
586 struct close_args *uap;
588 register struct filedesc *fdp = p->p_fd;
589 register struct file *fp;
590 register int fd = uap->fd;
594 if ((unsigned)fd >= fdp->fd_nfiles ||
595 (fp = fdp->fd_ofiles[fd]) == NULL)
598 if (fdp->fd_ofileflags[fd] & UF_MAPPED)
599 (void) munmapfd(p, fd);
601 fdp->fd_ofiles[fd] = NULL;
602 fdp->fd_ofileflags[fd] = 0;
604 if (p->p_fdtol != NULL) {
606 * Ask fdfree() to sleep to ensure that all relevant
607 * process leaders can be traversed in closef().
609 fdp->fd_holdleaderscount++;
614 * we now hold the fp reference that used to be owned by the descriptor
617 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
619 if (fd < fdp->fd_freefile)
620 fdp->fd_freefile = fd;
621 if (fd < fdp->fd_knlistsize)
622 knote_fdclose(p, fd);
623 error = closef(fp, p);
625 fdp->fd_holdleaderscount--;
626 if (fdp->fd_holdleaderscount == 0 &&
627 fdp->fd_holdleaderswakeup != 0) {
628 fdp->fd_holdleaderswakeup = 0;
629 wakeup(&fdp->fd_holdleaderscount);
635 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
637 * Return status information about a file descriptor.
639 #ifndef _SYS_SYSPROTO_H_
649 register struct ofstat_args *uap;
651 register struct filedesc *fdp = p->p_fd;
652 register struct file *fp;
657 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
658 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
661 error = fo_stat(fp, &ub, p);
664 error = copyout((caddr_t)&oub, (caddr_t)uap->sb, sizeof (oub));
669 #endif /* COMPAT_43 || COMPAT_SUNOS */
672 * Return status information about a file descriptor.
674 #ifndef _SYS_SYSPROTO_H_
684 register struct fstat_args *uap;
686 register struct filedesc *fdp = p->p_fd;
687 register struct file *fp;
691 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
692 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
695 error = fo_stat(fp, &ub, p);
697 error = copyout((caddr_t)&ub, (caddr_t)uap->sb, sizeof (ub));
703 * Return status information about a file descriptor.
705 #ifndef _SYS_SYSPROTO_H_
715 register struct nfstat_args *uap;
717 register struct filedesc *fdp = p->p_fd;
718 register struct file *fp;
723 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
724 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
727 error = fo_stat(fp, &ub, p);
730 error = copyout((caddr_t)&nub, (caddr_t)uap->sb, sizeof (nub));
737 * Return pathconf information about a file descriptor.
739 #ifndef _SYS_SYSPROTO_H_
740 struct fpathconf_args {
749 register struct fpathconf_args *uap;
751 struct filedesc *fdp = p->p_fd;
756 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
757 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
762 switch (fp->f_type) {
765 if (uap->name != _PC_PIPE_BUF) {
768 p->p_retval[0] = PIPE_BUF;
774 vp = (struct vnode *)fp->f_data;
775 error = VOP_PATHCONF(vp, uap->name, p->p_retval);
786 * Allocate a file descriptor for the process.
789 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
792 fdalloc(p, want, result)
797 register struct filedesc *fdp = p->p_fd;
799 int lim, last, nfiles;
800 struct file **newofile;
804 * Search for a free descriptor starting at the higher
805 * of want or fd_freefile. If that fails, consider
806 * expanding the ofile array.
808 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
810 last = min(fdp->fd_nfiles, lim);
811 if ((i = want) < fdp->fd_freefile)
812 i = fdp->fd_freefile;
813 for (; i < last; i++) {
814 if (fdp->fd_ofiles[i] == NULL) {
815 fdp->fd_ofileflags[i] = 0;
816 if (i > fdp->fd_lastfile)
817 fdp->fd_lastfile = i;
818 if (want <= fdp->fd_freefile)
819 fdp->fd_freefile = i;
826 * No space in current array. Expand?
828 if (fdp->fd_nfiles >= lim)
830 if (fdp->fd_nfiles < NDEXTENT)
833 nfiles = 2 * fdp->fd_nfiles;
834 MALLOC(newofile, struct file **, nfiles * OFILESIZE,
835 M_FILEDESC, M_WAITOK);
838 * deal with file-table extend race that might have occured
839 * when malloc was blocked.
841 if (fdp->fd_nfiles >= nfiles) {
842 FREE(newofile, M_FILEDESC);
845 newofileflags = (char *) &newofile[nfiles];
847 * Copy the existing ofile and ofileflags arrays
848 * and zero the new portion of each array.
850 bcopy(fdp->fd_ofiles, newofile,
851 (i = sizeof(struct file *) * fdp->fd_nfiles));
852 bzero((char *)newofile + i, nfiles * sizeof(struct file *) - i);
853 bcopy(fdp->fd_ofileflags, newofileflags,
854 (i = sizeof(char) * fdp->fd_nfiles));
855 bzero(newofileflags + i, nfiles * sizeof(char) - i);
856 if (fdp->fd_nfiles > NDFILE)
857 FREE(fdp->fd_ofiles, M_FILEDESC);
858 fdp->fd_ofiles = newofile;
859 fdp->fd_ofileflags = newofileflags;
860 fdp->fd_nfiles = nfiles;
867 * Check to see whether n user file descriptors
868 * are available to the process p.
875 register struct filedesc *fdp = p->p_fd;
876 register struct file **fpp;
877 register int i, lim, last;
879 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
880 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
883 last = min(fdp->fd_nfiles, lim);
884 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
885 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
886 if (*fpp == NULL && --n <= 0)
893 * Create a new open file structure and allocate
894 * a file decriptor for the process that refers to it.
897 falloc(p, resultfp, resultfd)
898 register struct proc *p;
899 struct file **resultfp;
902 register struct file *fp, *fq;
905 if (nfiles >= maxfiles) {
910 * Allocate a new file descriptor.
911 * If the process has file descriptor zero open, add to the list
912 * of open files at that point, otherwise put it at the front of
913 * the list of open files.
916 MALLOC(fp, struct file *, sizeof(struct file), M_FILE, M_WAITOK);
917 bzero(fp, sizeof(struct file));
920 * wait until after malloc (which may have blocked) returns before
921 * allocating the slot, else a race might have shrunk it if we had
922 * allocated it before the malloc.
924 if ((error = fdalloc(p, 0, &i))) {
930 fp->f_cred = p->p_ucred;
931 fp->f_ops = &badfileops;
934 if ((fq = p->p_fd->fd_ofiles[0])) {
935 LIST_INSERT_AFTER(fq, fp, f_list);
937 LIST_INSERT_HEAD(&filehead, fp, f_list);
939 p->p_fd->fd_ofiles[i] = fp;
948 * Free a file descriptor.
952 register struct file *fp;
954 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
955 LIST_REMOVE(fp, f_list);
962 * Build a new filedesc structure.
968 register struct filedesc0 *newfdp;
969 register struct filedesc *fdp = p->p_fd;
971 MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
972 M_FILEDESC, M_WAITOK);
973 bzero(newfdp, sizeof(struct filedesc0));
974 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
975 if (newfdp->fd_fd.fd_cdir)
976 VREF(newfdp->fd_fd.fd_cdir);
977 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
978 if (newfdp->fd_fd.fd_rdir)
979 VREF(newfdp->fd_fd.fd_rdir);
980 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
981 if (newfdp->fd_fd.fd_jdir)
982 VREF(newfdp->fd_fd.fd_jdir);
984 /* Create the file descriptor table. */
985 newfdp->fd_fd.fd_refcnt = 1;
986 newfdp->fd_fd.fd_cmask = cmask;
987 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
988 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
989 newfdp->fd_fd.fd_nfiles = NDFILE;
990 newfdp->fd_fd.fd_knlistsize = -1;
992 return (&newfdp->fd_fd);
996 * Share a filedesc structure.
1002 p->p_fd->fd_refcnt++;
1007 * Copy a filedesc structure.
1013 register struct filedesc *newfdp, *fdp = p->p_fd;
1014 register struct file **fpp;
1017 /* Certain daemons might not have file descriptors. */
1021 MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
1022 M_FILEDESC, M_WAITOK);
1023 bcopy(fdp, newfdp, sizeof(struct filedesc));
1024 if (newfdp->fd_cdir)
1025 VREF(newfdp->fd_cdir);
1026 if (newfdp->fd_rdir)
1027 VREF(newfdp->fd_rdir);
1028 if (newfdp->fd_jdir)
1029 VREF(newfdp->fd_jdir);
1030 newfdp->fd_refcnt = 1;
1033 * If the number of open files fits in the internal arrays
1034 * of the open file structure, use them, otherwise allocate
1035 * additional memory for the number of descriptors currently
1038 if (newfdp->fd_lastfile < NDFILE) {
1039 newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
1040 newfdp->fd_ofileflags =
1041 ((struct filedesc0 *) newfdp)->fd_dfileflags;
1045 * Compute the smallest multiple of NDEXTENT needed
1046 * for the file descriptors currently in use,
1047 * allowing the table to shrink.
1049 i = newfdp->fd_nfiles;
1050 while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
1052 MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
1053 M_FILEDESC, M_WAITOK);
1054 newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1056 newfdp->fd_nfiles = i;
1057 bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
1058 bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
1061 * kq descriptors cannot be copied.
1063 if (newfdp->fd_knlistsize != -1) {
1064 fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
1065 for (i = newfdp->fd_lastfile; i >= 0; i--, fpp--) {
1066 if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
1068 if (i < newfdp->fd_freefile)
1069 newfdp->fd_freefile = i;
1071 if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
1072 newfdp->fd_lastfile--;
1074 newfdp->fd_knlist = NULL;
1075 newfdp->fd_knlistsize = -1;
1076 newfdp->fd_knhash = NULL;
1077 newfdp->fd_knhashmask = 0;
1080 fpp = newfdp->fd_ofiles;
1081 for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
1089 * Release a filedesc structure.
1095 register struct filedesc *fdp = p->p_fd;
1098 struct filedesc_to_leader *fdtol;
1103 /* Certain daemons might not have file descriptors. */
1107 /* Check for special need to clear POSIX style locks */
1109 if (fdtol != NULL) {
1110 KASSERT(fdtol->fdl_refcount > 0,
1111 ("filedesc_to_refcount botch: fdl_refcount=%d",
1112 fdtol->fdl_refcount));
1113 if (fdtol->fdl_refcount == 1 &&
1114 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1116 fpp = fdp->fd_ofiles;
1117 for (i = 0, fpp = fdp->fd_ofiles;
1118 i < fdp->fd_lastfile;
1121 (*fpp)->f_type != DTYPE_VNODE)
1125 lf.l_whence = SEEK_SET;
1128 lf.l_type = F_UNLCK;
1129 vp = (struct vnode *)fp->f_data;
1130 (void) VOP_ADVLOCK(vp,
1131 (caddr_t)p->p_leader,
1136 fpp = fdp->fd_ofiles + i;
1140 if (fdtol->fdl_refcount == 1) {
1141 if (fdp->fd_holdleaderscount > 0 &&
1142 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1144 * close() or do_dup() has cleared a reference
1145 * in a shared file descriptor table.
1147 fdp->fd_holdleaderswakeup = 1;
1148 tsleep(&fdp->fd_holdleaderscount,
1149 PLOCK, "fdlhold", 0);
1152 if (fdtol->fdl_holdcount > 0) {
1154 * Ensure that fdtol->fdl_leader
1155 * remains valid in closef().
1157 fdtol->fdl_wakeup = 1;
1158 tsleep(fdtol, PLOCK, "fdlhold", 0);
1162 fdtol->fdl_refcount--;
1163 if (fdtol->fdl_refcount == 0 &&
1164 fdtol->fdl_holdcount == 0) {
1165 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1166 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1171 FREE(fdtol, M_FILEDESC_TO_LEADER);
1173 if (--fdp->fd_refcnt > 0)
1176 * we are the last reference to the structure, we can
1177 * safely assume it will not change out from under us.
1179 fpp = fdp->fd_ofiles;
1180 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1182 (void) closef(*fpp, p);
1184 if (fdp->fd_nfiles > NDFILE)
1185 FREE(fdp->fd_ofiles, M_FILEDESC);
1187 vrele(fdp->fd_cdir);
1189 vrele(fdp->fd_rdir);
1191 vrele(fdp->fd_jdir);
1193 FREE(fdp->fd_knlist, M_KQUEUE);
1195 FREE(fdp->fd_knhash, M_KQUEUE);
1196 FREE(fdp, M_FILEDESC);
1200 * For setugid programs, we don't want to people to use that setugidness
1201 * to generate error messages which write to a file which otherwise would
1202 * otherwise be off-limits to the process.
1204 * This is a gross hack to plug the hole. A better solution would involve
1205 * a special vop or other form of generalized access control mechanism. We
1206 * go ahead and just reject all procfs file systems accesses as dangerous.
1208 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1209 * sufficient. We also don't for check setugidness since we know we are.
1212 is_unsafe(struct file *fp)
1214 if (fp->f_type == DTYPE_VNODE &&
1215 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1221 * Make this setguid thing safe, if at all possible.
1227 struct filedesc *fdp = p->p_fd;
1230 /* Certain daemons might not have file descriptors. */
1235 * note: fdp->fd_ofiles may be reallocated out from under us while
1236 * we are blocked in a close. Be careful!
1238 for (i = 0; i <= fdp->fd_lastfile; i++) {
1241 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1245 if ((fdp->fd_ofileflags[i] & UF_MAPPED) != 0)
1246 (void) munmapfd(p, i);
1248 if (i < fdp->fd_knlistsize)
1249 knote_fdclose(p, i);
1251 * NULL-out descriptor prior to close to avoid
1252 * a race while close blocks.
1254 fp = fdp->fd_ofiles[i];
1255 fdp->fd_ofiles[i] = NULL;
1256 fdp->fd_ofileflags[i] = 0;
1257 if (i < fdp->fd_freefile)
1258 fdp->fd_freefile = i;
1259 (void) closef(fp, p);
1262 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1267 * Close any files on exec?
1273 struct filedesc *fdp = p->p_fd;
1276 /* Certain daemons might not have file descriptors. */
1281 * We cannot cache fd_ofiles or fd_ofileflags since operations
1282 * may block and rip them out from under us.
1284 for (i = 0; i <= fdp->fd_lastfile; i++) {
1285 if (fdp->fd_ofiles[i] != NULL &&
1286 (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1290 if (fdp->fd_ofileflags[i] & UF_MAPPED)
1291 (void) munmapfd(p, i);
1293 if (i < fdp->fd_knlistsize)
1294 knote_fdclose(p, i);
1296 * NULL-out descriptor prior to close to avoid
1297 * a race while close blocks.
1299 fp = fdp->fd_ofiles[i];
1300 fdp->fd_ofiles[i] = NULL;
1301 fdp->fd_ofileflags[i] = 0;
1302 if (i < fdp->fd_freefile)
1303 fdp->fd_freefile = i;
1304 (void) closef(fp, p);
1307 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1312 * It is unsafe for set[ug]id processes to be started with file
1313 * descriptors 0..2 closed, as these descriptors are given implicit
1314 * significance in the Standard C library. fdcheckstd() will create a
1315 * descriptor referencing /dev/null for each of stdin, stdout, and
1316 * stderr that is not already open.
1322 struct nameidata nd;
1323 struct filedesc *fdp;
1326 int fd, i, error, flags, devnull;
1333 for (i = 0; i < 3; i++) {
1334 if (fdp->fd_ofiles[i] != NULL)
1337 error = falloc(p, &fp, &fd);
1340 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/null",
1342 flags = FREAD | FWRITE;
1343 error = vn_open(&nd, flags, 0);
1345 fdp->fd_ofiles[i] = NULL;
1349 NDFREE(&nd, NDF_ONLY_PNBUF);
1350 fp->f_data = (caddr_t)nd.ni_vp;
1353 fp->f_type = DTYPE_VNODE;
1354 VOP_UNLOCK(nd.ni_vp, 0, p);
1357 error = fdalloc(p, 0, &fd);
1360 error = do_dup(fdp, devnull, fd, &retval, p);
1369 * Internal form of close.
1370 * Decrement reference count on file structure.
1371 * Note: p may be NULL when closing a file
1372 * that was being passed in a message.
1376 register struct file *fp;
1377 register struct proc *p;
1381 struct filedesc_to_leader *fdtol;
1386 * POSIX record locking dictates that any close releases ALL
1387 * locks owned by this process. This is handled by setting
1388 * a flag in the unlock to free ONLY locks obeying POSIX
1389 * semantics, and not to free BSD-style file locks.
1390 * If the descriptor was in a message, POSIX-style locks
1391 * aren't passed with the descriptor.
1394 fp->f_type == DTYPE_VNODE) {
1395 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1396 lf.l_whence = SEEK_SET;
1399 lf.l_type = F_UNLCK;
1400 vp = (struct vnode *)fp->f_data;
1401 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1405 if (fdtol != NULL) {
1407 * Handle special case where file descriptor table
1408 * is shared between multiple process leaders.
1410 for (fdtol = fdtol->fdl_next;
1411 fdtol != p->p_fdtol;
1412 fdtol = fdtol->fdl_next) {
1413 if ((fdtol->fdl_leader->p_flag &
1416 fdtol->fdl_holdcount++;
1417 lf.l_whence = SEEK_SET;
1420 lf.l_type = F_UNLCK;
1421 vp = (struct vnode *)fp->f_data;
1422 (void) VOP_ADVLOCK(vp,
1423 (caddr_t)p->p_leader,
1424 F_UNLCK, &lf, F_POSIX);
1425 fdtol->fdl_holdcount--;
1426 if (fdtol->fdl_holdcount == 0 &&
1427 fdtol->fdl_wakeup != 0) {
1428 fdtol->fdl_wakeup = 0;
1434 return (fdrop(fp, p));
1446 if (--fp->f_count > 0)
1448 if (fp->f_count < 0)
1449 panic("fdrop: count < 0");
1450 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1451 lf.l_whence = SEEK_SET;
1454 lf.l_type = F_UNLCK;
1455 vp = (struct vnode *)fp->f_data;
1456 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1458 if (fp->f_ops != &badfileops)
1459 error = fo_close(fp, p);
1467 * Apply an advisory lock on a file descriptor.
1469 * Just attempt to get a record lock of the requested type on
1470 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1472 #ifndef _SYS_SYSPROTO_H_
1482 register struct flock_args *uap;
1484 register struct filedesc *fdp = p->p_fd;
1485 register struct file *fp;
1489 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1490 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1492 if (fp->f_type != DTYPE_VNODE)
1493 return (EOPNOTSUPP);
1494 vp = (struct vnode *)fp->f_data;
1495 lf.l_whence = SEEK_SET;
1498 if (uap->how & LOCK_UN) {
1499 lf.l_type = F_UNLCK;
1500 fp->f_flag &= ~FHASLOCK;
1501 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1503 if (uap->how & LOCK_EX)
1504 lf.l_type = F_WRLCK;
1505 else if (uap->how & LOCK_SH)
1506 lf.l_type = F_RDLCK;
1509 fp->f_flag |= FHASLOCK;
1510 if (uap->how & LOCK_NB)
1511 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1512 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1516 * File Descriptor pseudo-device driver (/dev/fd/).
1518 * Opening minor device N dup()s the file (if any) connected to file
1519 * descriptor N belonging to the calling process. Note that this driver
1520 * consists of only the ``open()'' routine, because all subsequent
1521 * references to this file will be direct to the other driver.
1525 fdopen(dev, mode, type, p)
1532 * XXX Kludge: set curproc->p_dupfd to contain the value of the
1533 * the file descriptor being sought for duplication. The error
1534 * return ensures that the vnode for this device will be released
1535 * by vn_open. Open will detect this special error and take the
1536 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1537 * will simply report the error.
1539 p->p_dupfd = minor(dev);
1544 * Duplicate the specified descriptor to a free descriptor.
1547 dupfdopen(p, fdp, indx, dfd, mode, error)
1549 struct filedesc *fdp;
1554 register struct file *wfp;
1558 * If the to-be-dup'd fd number is greater than the allowed number
1559 * of file descriptors, or the fd to be dup'd has already been
1560 * closed, then reject.
1562 if ((u_int)dfd >= fdp->fd_nfiles ||
1563 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
1568 * There are two cases of interest here.
1570 * For ENODEV simply dup (dfd) to file descriptor
1571 * (indx) and return.
1573 * For ENXIO steal away the file structure from (dfd) and
1574 * store it in (indx). (dfd) is effectively closed by
1577 * Any other error code is just returned.
1582 * Check that the mode the file is being opened for is a
1583 * subset of the mode of the existing descriptor.
1585 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1587 fp = fdp->fd_ofiles[indx];
1589 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1590 (void) munmapfd(p, indx);
1592 fdp->fd_ofiles[indx] = wfp;
1593 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1595 if (indx > fdp->fd_lastfile)
1596 fdp->fd_lastfile = indx;
1598 * we now own the reference to fp that the ofiles[] array
1599 * used to own. Release it.
1607 * Steal away the file pointer from dfd, and stuff it into indx.
1609 fp = fdp->fd_ofiles[indx];
1611 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1612 (void) munmapfd(p, indx);
1614 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
1615 fdp->fd_ofiles[dfd] = NULL;
1616 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1617 fdp->fd_ofileflags[dfd] = 0;
1620 * we now own the reference to fp that the ofiles[] array
1621 * used to own. Release it.
1626 * Complete the clean up of the filedesc structure by
1627 * recomputing the various hints.
1629 if (indx > fdp->fd_lastfile) {
1630 fdp->fd_lastfile = indx;
1632 while (fdp->fd_lastfile > 0 &&
1633 fdp->fd_ofiles[fdp->fd_lastfile] == NULL) {
1636 if (dfd < fdp->fd_freefile)
1637 fdp->fd_freefile = dfd;
1648 struct filedesc_to_leader *
1649 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1650 struct proc *leader)
1652 struct filedesc_to_leader *fdtol;
1654 MALLOC(fdtol, struct filedesc_to_leader *,
1655 sizeof(struct filedesc_to_leader),
1656 M_FILEDESC_TO_LEADER,
1658 fdtol->fdl_refcount = 1;
1659 fdtol->fdl_holdcount = 0;
1660 fdtol->fdl_wakeup = 0;
1661 fdtol->fdl_leader = leader;
1663 fdtol->fdl_next = old->fdl_next;
1664 fdtol->fdl_prev = old;
1665 old->fdl_next = fdtol;
1666 fdtol->fdl_next->fdl_prev = fdtol;
1668 fdtol->fdl_next = fdtol;
1669 fdtol->fdl_prev = fdtol;
1675 * Get file structures.
1678 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1685 * overestimate by 10 files
1687 return (SYSCTL_OUT(req, 0, sizeof(filehead) +
1688 (nfiles + 10) * sizeof(struct file)));
1691 error = SYSCTL_OUT(req, (caddr_t)&filehead, sizeof(filehead));
1696 * followed by an array of file structures
1698 LIST_FOREACH(fp, &filehead, f_list) {
1699 error = SYSCTL_OUT(req, (caddr_t)fp, sizeof (struct file));
1706 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1707 0, 0, sysctl_kern_file, "S,file", "Entire file table");
1709 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
1710 &maxfilesperproc, 0, "Maximum files allowed open per process");
1712 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
1713 &maxfiles, 0, "Maximum number of files");
1715 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
1716 &nfiles, 0, "System-wide number of open files");
1719 fildesc_drvinit(void *unused)
1723 for (fd = 0; fd < NUMFDESC; fd++)
1724 make_dev(&fildesc_cdevsw, fd,
1725 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1726 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1727 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1728 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1731 struct fileops badfileops = {
1742 badfo_readwrite(fp, uio, cred, flags, p)
1754 badfo_ioctl(fp, com, data, p)
1765 badfo_poll(fp, events, cred, p)
1776 badfo_kqfilter(fp, kn)
1785 badfo_stat(fp, sb, p)
1803 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1804 fildesc_drvinit,NULL)