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.19 2004/02/28 00:43:31 tegge Exp $
40 * $DragonFly: src/sys/kern/kern_descrip.c,v 1.21 2004/04/21 06:09:52 dillon Exp $
43 #include "opt_compat.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/malloc.h>
47 #include <sys/sysproto.h>
49 #include <sys/filedesc.h>
50 #include <sys/kernel.h>
51 #include <sys/sysctl.h>
52 #include <sys/vnode.h>
54 #include <sys/namei.h>
57 #include <sys/filio.h>
58 #include <sys/fcntl.h>
59 #include <sys/unistd.h>
60 #include <sys/resourcevar.h>
61 #include <sys/event.h>
62 #include <sys/kern_syscall.h>
65 #include <vm/vm_extern.h>
67 #include <sys/file2.h>
69 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
70 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
71 "file desc to leader structures");
72 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
73 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
75 static d_open_t fdopen;
79 static struct cdevsw fildesc_cdevsw = {
93 /* strategy */ nostrategy,
98 static int badfo_readwrite (struct file *fp, struct uio *uio,
99 struct ucred *cred, int flags, struct thread *td);
100 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
102 static int badfo_poll (struct file *fp, int events,
103 struct ucred *cred, struct thread *td);
104 static int badfo_kqfilter (struct file *fp, struct knote *kn);
105 static int badfo_stat (struct file *fp, struct stat *sb, struct thread *td);
106 static int badfo_close (struct file *fp, struct thread *td);
109 * Descriptor management.
111 struct filelist filehead; /* head of list of open files */
112 int nfiles; /* actual number of open files */
116 * System calls on descriptors.
120 getdtablesize(struct getdtablesize_args *uap)
122 struct proc *p = curproc;
125 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
130 * Duplicate a file descriptor to a particular value.
132 * note: keep in mind that a potential race condition exists when closing
133 * descriptors from a shared descriptor table (via rfork).
137 dup2(struct dup2_args *uap)
141 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
147 * Duplicate a file descriptor.
151 dup(struct dup_args *uap)
155 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
161 kern_fcntl(int fd, int cmd, union fcntl_dat *dat)
163 struct thread *td = curthread;
164 struct proc *p = td->td_proc;
165 struct filedesc *fdp = p->p_fd;
170 int tmp, error, flg = F_POSIX;
174 if ((unsigned)fd >= fdp->fd_nfiles ||
175 (fp = fdp->fd_ofiles[fd]) == NULL)
177 pop = &fdp->fd_ofileflags[fd];
182 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
183 newmin > maxfilesperproc)
185 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
189 dat->fc_cloexec = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
193 *pop = (*pop &~ UF_EXCLOSE) |
194 (dat->fc_cloexec & FD_CLOEXEC ? UF_EXCLOSE : 0);
198 dat->fc_flags = OFLAGS(fp->f_flag);
203 fp->f_flag &= ~FCNTLFLAGS;
204 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
205 tmp = fp->f_flag & FNONBLOCK;
206 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
211 tmp = fp->f_flag & FASYNC;
212 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
217 fp->f_flag &= ~FNONBLOCK;
219 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
225 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, td);
231 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, td);
237 /* Fall into F_SETLK */
240 if (fp->f_type != DTYPE_VNODE)
242 vp = (struct vnode *)fp->f_data;
245 * copyin/lockop may block
248 if (dat->fc_flock.l_whence == SEEK_CUR)
249 dat->fc_flock.l_start += fp->f_offset;
251 switch (dat->fc_flock.l_type) {
253 if ((fp->f_flag & FREAD) == 0) {
257 p->p_leader->p_flag |= P_ADVLOCK;
258 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
259 &dat->fc_flock, flg);
262 if ((fp->f_flag & FWRITE) == 0) {
266 p->p_leader->p_flag |= P_ADVLOCK;
267 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
268 &dat->fc_flock, flg);
271 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
272 &dat->fc_flock, F_POSIX);
278 /* Check for race with close */
279 if ((unsigned) fd >= fdp->fd_nfiles ||
280 fp != fdp->fd_ofiles[fd]) {
281 dat->fc_flock.l_whence = SEEK_SET;
282 dat->fc_flock.l_start = 0;
283 dat->fc_flock.l_len = 0;
284 dat->fc_flock.l_type = F_UNLCK;
285 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
286 F_UNLCK, &dat->fc_flock, F_POSIX);
292 if (fp->f_type != DTYPE_VNODE)
294 vp = (struct vnode *)fp->f_data;
296 * copyin/lockop may block
299 if (dat->fc_flock.l_type != F_RDLCK &&
300 dat->fc_flock.l_type != F_WRLCK &&
301 dat->fc_flock.l_type != F_UNLCK) {
305 if (dat->fc_flock.l_whence == SEEK_CUR)
306 dat->fc_flock.l_start += fp->f_offset;
307 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
308 &dat->fc_flock, F_POSIX);
318 * The file control system call.
321 fcntl(struct fcntl_args *uap)
328 dat.fc_fd = uap->arg;
331 dat.fc_cloexec = uap->arg;
334 dat.fc_flags = uap->arg;
337 dat.fc_owner = uap->arg;
342 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
343 sizeof(struct flock));
349 error = kern_fcntl(uap->fd, uap->cmd, &dat);
354 uap->sysmsg_result = dat.fc_fd;
357 uap->sysmsg_result = dat.fc_cloexec;
360 uap->sysmsg_result = dat.fc_flags;
363 uap->sysmsg_result = dat.fc_owner;
365 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
366 sizeof(struct flock));
375 * Common code for dup, dup2, and fcntl(F_DUPFD).
377 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
378 * kern_dup() to destructively dup over an existing file descriptor if new
379 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
380 * unused file descriptor that is greater than or equal to new.
383 kern_dup(enum dup_type type, int old, int new, int *res)
385 struct thread *td = curthread;
386 struct proc *p = td->td_proc;
387 struct filedesc *fdp = p->p_fd;
394 * Verify that we have a valid descriptor to dup from and
395 * possibly to dup to.
397 if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
398 new >= maxfilesperproc)
400 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
402 if (type == DUP_FIXED && old == new) {
406 fp = fdp->fd_ofiles[old];
410 * Expand the table for the new descriptor if needed. This may
411 * block and drop and reacquire the fidedesc lock.
413 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
414 error = fdalloc(p, new, &newfd);
420 if (type == DUP_VARIABLE)
424 * If the old file changed out from under us then treat it as a
425 * bad file descriptor. Userland should do its own locking to
428 if (fdp->fd_ofiles[old] != fp) {
429 if (fdp->fd_ofiles[new] == NULL) {
430 if (new < fdp->fd_freefile)
431 fdp->fd_freefile = new;
432 while (fdp->fd_lastfile > 0 &&
433 fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
439 KASSERT(old != new, ("new fd is same as old"));
442 * Save info on the descriptor being overwritten. We have
443 * to do the unmap now, but we cannot close it without
444 * introducing an ownership race for the slot.
446 delfp = fdp->fd_ofiles[new];
447 if (delfp != NULL && p->p_fdtol != NULL) {
449 * Ask fdfree() to sleep to ensure that all relevant
450 * process leaders can be traversed in closef().
452 fdp->fd_holdleaderscount++;
456 KASSERT(delfp == NULL || type == DUP_FIXED,
457 ("dup() picked an open file"));
459 if (delfp && (fdp->fd_ofileflags[new] & UF_MAPPED))
460 (void) munmapfd(p, new);
464 * Duplicate the source descriptor, update lastfile
466 fdp->fd_ofiles[new] = fp;
467 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
468 if (new > fdp->fd_lastfile)
469 fdp->fd_lastfile = new;
473 * If we dup'd over a valid file, we now own the reference to it
474 * and must dispose of it using closef() semantics (as if a
475 * close() were performed on it).
478 (void) closef(delfp, td);
480 fdp->fd_holdleaderscount--;
481 if (fdp->fd_holdleaderscount == 0 &&
482 fdp->fd_holdleaderswakeup != 0) {
483 fdp->fd_holdleaderswakeup = 0;
484 wakeup(&fdp->fd_holdleaderscount);
492 * If sigio is on the list associated with a process or process group,
493 * disable signalling from the device, remove sigio from the list and
505 *(sigio->sio_myref) = NULL;
507 if (sigio->sio_pgid < 0) {
508 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
510 } else /* if ((*sigiop)->sio_pgid > 0) */ {
511 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
514 crfree(sigio->sio_ucred);
515 FREE(sigio, M_SIGIO);
518 /* Free a list of sigio structures. */
520 funsetownlst(sigiolst)
521 struct sigiolst *sigiolst;
525 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
530 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
532 * After permission checking, add a sigio structure to the sigio list for
533 * the process or process group.
536 fsetown(pgid, sigiop)
538 struct sigio **sigiop;
555 * Policy - Don't allow a process to FSETOWN a process
556 * in another session.
558 * Remove this test to allow maximum flexibility or
559 * restrict FSETOWN to the current process or process
560 * group for maximum safety.
562 if (proc->p_session != curproc->p_session)
566 } else /* if (pgid < 0) */ {
567 pgrp = pgfind(-pgid);
572 * Policy - Don't allow a process to FSETOWN a process
573 * in another session.
575 * Remove this test to allow maximum flexibility or
576 * restrict FSETOWN to the current process or process
577 * group for maximum safety.
579 if (pgrp->pg_session != curproc->p_session)
585 MALLOC(sigio, struct sigio *, sizeof(struct sigio), M_SIGIO, M_WAITOK);
587 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
588 sigio->sio_proc = proc;
590 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
591 sigio->sio_pgrp = pgrp;
593 sigio->sio_pgid = pgid;
594 sigio->sio_ucred = crhold(curproc->p_ucred);
595 /* It would be convenient if p_ruid was in ucred. */
596 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
597 sigio->sio_myref = sigiop;
605 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
611 return (sigio != NULL ? sigio->sio_pgid : 0);
615 * Close a file descriptor.
619 close(struct close_args *uap)
621 struct thread *td = curthread;
622 struct proc *p = td->td_proc;
623 struct filedesc *fdp;
632 if ((unsigned)fd >= fdp->fd_nfiles ||
633 (fp = fdp->fd_ofiles[fd]) == NULL)
636 if (fdp->fd_ofileflags[fd] & UF_MAPPED)
637 (void) munmapfd(p, fd);
639 fdp->fd_ofiles[fd] = NULL;
640 fdp->fd_ofileflags[fd] = 0;
642 if (p->p_fdtol != NULL) {
644 * Ask fdfree() to sleep to ensure that all relevant
645 * process leaders can be traversed in closef().
647 fdp->fd_holdleaderscount++;
652 * we now hold the fp reference that used to be owned by the descriptor
655 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
657 if (fd < fdp->fd_freefile)
658 fdp->fd_freefile = fd;
659 if (fd < fdp->fd_knlistsize)
660 knote_fdclose(p, fd);
661 error = closef(fp, td);
663 fdp->fd_holdleaderscount--;
664 if (fdp->fd_holdleaderscount == 0 &&
665 fdp->fd_holdleaderswakeup != 0) {
666 fdp->fd_holdleaderswakeup = 0;
667 wakeup(&fdp->fd_holdleaderscount);
674 kern_fstat(int fd, struct stat *ub)
676 struct thread *td = curthread;
677 struct proc *p = td->td_proc;
678 struct filedesc *fdp;
685 if ((unsigned)fd >= fdp->fd_nfiles ||
686 (fp = fdp->fd_ofiles[fd]) == NULL)
689 error = fo_stat(fp, ub, td);
696 * Return status information about a file descriptor.
699 fstat(struct fstat_args *uap)
704 error = kern_fstat(uap->fd, &st);
707 error = copyout(&st, uap->sb, sizeof(st));
712 * XXX: This is for source compatibility with NetBSD. Probably doesn't
716 nfstat(struct nfstat_args *uap)
722 error = kern_fstat(uap->fd, &st);
726 error = copyout(&nst, uap->sb, sizeof (nst));
732 * Return pathconf information about a file descriptor.
736 fpathconf(struct fpathconf_args *uap)
738 struct thread *td = curthread;
739 struct proc *p = td->td_proc;
740 struct filedesc *fdp;
747 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
748 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
753 switch (fp->f_type) {
756 if (uap->name != _PC_PIPE_BUF) {
759 uap->sysmsg_result = PIPE_BUF;
765 vp = (struct vnode *)fp->f_data;
766 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
777 * Allocate a file descriptor for the process.
780 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
783 fdalloc(struct proc *p, int want, int *result)
785 struct filedesc *fdp = p->p_fd;
787 int lim, last, nfiles;
788 struct file **newofile;
792 * Search for a free descriptor starting at the higher
793 * of want or fd_freefile. If that fails, consider
794 * expanding the ofile array.
796 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
798 last = min(fdp->fd_nfiles, lim);
799 if ((i = want) < fdp->fd_freefile)
800 i = fdp->fd_freefile;
801 for (; i < last; i++) {
802 if (fdp->fd_ofiles[i] == NULL) {
803 fdp->fd_ofileflags[i] = 0;
804 if (i > fdp->fd_lastfile)
805 fdp->fd_lastfile = i;
806 if (want <= fdp->fd_freefile)
807 fdp->fd_freefile = i;
814 * No space in current array. Expand?
816 if (fdp->fd_nfiles >= lim)
818 if (fdp->fd_nfiles < NDEXTENT)
821 nfiles = 2 * fdp->fd_nfiles;
822 MALLOC(newofile, struct file **, nfiles * OFILESIZE,
823 M_FILEDESC, M_WAITOK);
826 * deal with file-table extend race that might have occured
827 * when malloc was blocked.
829 if (fdp->fd_nfiles >= nfiles) {
830 FREE(newofile, M_FILEDESC);
833 newofileflags = (char *) &newofile[nfiles];
835 * Copy the existing ofile and ofileflags arrays
836 * and zero the new portion of each array.
838 bcopy(fdp->fd_ofiles, newofile,
839 (i = sizeof(struct file *) * fdp->fd_nfiles));
840 bzero((char *)newofile + i, nfiles * sizeof(struct file *) - i);
841 bcopy(fdp->fd_ofileflags, newofileflags,
842 (i = sizeof(char) * fdp->fd_nfiles));
843 bzero(newofileflags + i, nfiles * sizeof(char) - i);
844 if (fdp->fd_nfiles > NDFILE)
845 FREE(fdp->fd_ofiles, M_FILEDESC);
846 fdp->fd_ofiles = newofile;
847 fdp->fd_ofileflags = newofileflags;
848 fdp->fd_nfiles = nfiles;
855 * Check to see whether n user file descriptors
856 * are available to the process p.
863 struct filedesc *fdp = p->p_fd;
867 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
868 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
871 last = min(fdp->fd_nfiles, lim);
872 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
873 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
874 if (*fpp == NULL && --n <= 0)
882 * Create a new open file structure and allocate a file decriptor
883 * for the process that refers to it. If p is NULL, no descriptor
884 * is allocated and the file pointer is returned unassociated with
885 * any process. resultfd is only used if p is not NULL and may
886 * separately be NULL indicating that you don't need the returned fd.
889 falloc(struct proc *p, struct file **resultfp, int *resultfd)
891 struct file *fp, *fq;
893 static struct timeval lastfail;
896 if (nfiles >= maxfiles - maxfilesrootres &&
897 (p->p_ucred->cr_ruid != 0 || nfiles >= maxfiles)) {
898 if (ppsratecheck(&lastfail, &curfail, 1)) {
899 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
900 p->p_ucred->cr_ruid);
905 * Allocate a new file descriptor.
906 * If the process has file descriptor zero open, add to the list
907 * of open files at that point, otherwise put it at the front of
908 * the list of open files.
911 MALLOC(fp, struct file *, sizeof(struct file), M_FILE, M_WAITOK);
912 bzero(fp, sizeof(struct file));
915 * wait until after malloc (which may have blocked) returns before
916 * allocating the slot, else a race might have shrunk it if we had
917 * allocated it before the malloc.
920 if (p && (error = fdalloc(p, 0, &i))) {
926 fp->f_ops = &badfileops;
929 fp->f_cred = crhold(p->p_ucred);
930 if ((fq = p->p_fd->fd_ofiles[0]) != NULL) {
931 LIST_INSERT_AFTER(fq, fp, f_list);
933 LIST_INSERT_HEAD(&filehead, fp, f_list);
935 p->p_fd->fd_ofiles[i] = fp;
937 fp->f_cred = crhold(proc0.p_ucred);
938 LIST_INSERT_HEAD(&filehead, fp, f_list);
948 fsetcred(struct file *fp, struct ucred *cr)
956 * Free a file descriptor.
962 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
963 LIST_REMOVE(fp, f_list);
970 * Build a new filedesc structure.
976 struct filedesc0 *newfdp;
977 struct filedesc *fdp = p->p_fd;
979 MALLOC(newfdp, struct filedesc0 *, sizeof(struct filedesc0),
980 M_FILEDESC, M_WAITOK);
981 bzero(newfdp, sizeof(struct filedesc0));
982 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
983 if (newfdp->fd_fd.fd_cdir)
984 VREF(newfdp->fd_fd.fd_cdir);
985 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
986 if (newfdp->fd_fd.fd_rdir)
987 VREF(newfdp->fd_fd.fd_rdir);
988 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
989 if (newfdp->fd_fd.fd_jdir)
990 VREF(newfdp->fd_fd.fd_jdir);
992 /* Create the file descriptor table. */
993 newfdp->fd_fd.fd_refcnt = 1;
994 newfdp->fd_fd.fd_cmask = cmask;
995 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
996 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
997 newfdp->fd_fd.fd_nfiles = NDFILE;
998 newfdp->fd_fd.fd_knlistsize = -1;
1000 return (&newfdp->fd_fd);
1004 * Share a filedesc structure.
1010 p->p_fd->fd_refcnt++;
1015 * Copy a filedesc structure.
1021 struct filedesc *newfdp, *fdp = p->p_fd;
1025 /* Certain daemons might not have file descriptors. */
1029 MALLOC(newfdp, struct filedesc *, sizeof(struct filedesc0),
1030 M_FILEDESC, M_WAITOK);
1031 bcopy(fdp, newfdp, sizeof(struct filedesc));
1032 if (newfdp->fd_cdir)
1033 VREF(newfdp->fd_cdir);
1034 if (newfdp->fd_rdir)
1035 VREF(newfdp->fd_rdir);
1036 if (newfdp->fd_jdir)
1037 VREF(newfdp->fd_jdir);
1038 newfdp->fd_refcnt = 1;
1041 * If the number of open files fits in the internal arrays
1042 * of the open file structure, use them, otherwise allocate
1043 * additional memory for the number of descriptors currently
1046 if (newfdp->fd_lastfile < NDFILE) {
1047 newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
1048 newfdp->fd_ofileflags =
1049 ((struct filedesc0 *) newfdp)->fd_dfileflags;
1053 * Compute the smallest multiple of NDEXTENT needed
1054 * for the file descriptors currently in use,
1055 * allowing the table to shrink.
1057 i = newfdp->fd_nfiles;
1058 while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
1060 MALLOC(newfdp->fd_ofiles, struct file **, i * OFILESIZE,
1061 M_FILEDESC, M_WAITOK);
1062 newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1064 newfdp->fd_nfiles = i;
1065 bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
1066 bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
1069 * kq descriptors cannot be copied.
1071 if (newfdp->fd_knlistsize != -1) {
1072 fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
1073 for (i = newfdp->fd_lastfile; i >= 0; i--, fpp--) {
1074 if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
1076 if (i < newfdp->fd_freefile)
1077 newfdp->fd_freefile = i;
1079 if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
1080 newfdp->fd_lastfile--;
1082 newfdp->fd_knlist = NULL;
1083 newfdp->fd_knlistsize = -1;
1084 newfdp->fd_knhash = NULL;
1085 newfdp->fd_knhashmask = 0;
1088 fpp = newfdp->fd_ofiles;
1089 for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
1097 * Release a filedesc structure.
1100 fdfree(struct proc *p)
1102 struct thread *td = p->p_thread;
1103 struct filedesc *fdp = p->p_fd;
1106 struct filedesc_to_leader *fdtol;
1111 /* Certain daemons might not have file descriptors. */
1115 /* Check for special need to clear POSIX style locks */
1117 if (fdtol != NULL) {
1118 KASSERT(fdtol->fdl_refcount > 0,
1119 ("filedesc_to_refcount botch: fdl_refcount=%d",
1120 fdtol->fdl_refcount));
1121 if (fdtol->fdl_refcount == 1 &&
1122 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1124 fpp = fdp->fd_ofiles;
1125 for (i = 0, fpp = fdp->fd_ofiles;
1126 i <= fdp->fd_lastfile;
1129 (*fpp)->f_type != DTYPE_VNODE)
1133 lf.l_whence = SEEK_SET;
1136 lf.l_type = F_UNLCK;
1137 vp = (struct vnode *)fp->f_data;
1138 (void) VOP_ADVLOCK(vp,
1139 (caddr_t)p->p_leader,
1143 fdrop(fp, p->p_thread);
1144 fpp = fdp->fd_ofiles + i;
1148 if (fdtol->fdl_refcount == 1) {
1149 if (fdp->fd_holdleaderscount > 0 &&
1150 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1152 * close() or do_dup() has cleared a reference
1153 * in a shared file descriptor table.
1155 fdp->fd_holdleaderswakeup = 1;
1156 tsleep(&fdp->fd_holdleaderscount,
1160 if (fdtol->fdl_holdcount > 0) {
1162 * Ensure that fdtol->fdl_leader
1163 * remains valid in closef().
1165 fdtol->fdl_wakeup = 1;
1166 tsleep(fdtol, 0, "fdlhold", 0);
1170 fdtol->fdl_refcount--;
1171 if (fdtol->fdl_refcount == 0 &&
1172 fdtol->fdl_holdcount == 0) {
1173 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1174 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1179 FREE(fdtol, M_FILEDESC_TO_LEADER);
1181 if (--fdp->fd_refcnt > 0)
1184 * we are the last reference to the structure, we can
1185 * safely assume it will not change out from under us.
1187 fpp = fdp->fd_ofiles;
1188 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1190 (void) closef(*fpp, td);
1192 if (fdp->fd_nfiles > NDFILE)
1193 FREE(fdp->fd_ofiles, M_FILEDESC);
1195 vrele(fdp->fd_cdir);
1197 vrele(fdp->fd_rdir);
1199 vrele(fdp->fd_jdir);
1201 FREE(fdp->fd_knlist, M_KQUEUE);
1203 FREE(fdp->fd_knhash, M_KQUEUE);
1204 FREE(fdp, M_FILEDESC);
1208 * For setugid programs, we don't want to people to use that setugidness
1209 * to generate error messages which write to a file which otherwise would
1210 * otherwise be off-limits to the process.
1212 * This is a gross hack to plug the hole. A better solution would involve
1213 * a special vop or other form of generalized access control mechanism. We
1214 * go ahead and just reject all procfs file systems accesses as dangerous.
1216 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1217 * sufficient. We also don't for check setugidness since we know we are.
1220 is_unsafe(struct file *fp)
1222 if (fp->f_type == DTYPE_VNODE &&
1223 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1229 * Make this setguid thing safe, if at all possible.
1232 setugidsafety(struct proc *p)
1234 struct thread *td = p->p_thread;
1235 struct filedesc *fdp = p->p_fd;
1238 /* Certain daemons might not have file descriptors. */
1243 * note: fdp->fd_ofiles may be reallocated out from under us while
1244 * we are blocked in a close. Be careful!
1246 for (i = 0; i <= fdp->fd_lastfile; i++) {
1249 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1253 if ((fdp->fd_ofileflags[i] & UF_MAPPED) != 0)
1254 (void) munmapfd(p, i);
1256 if (i < fdp->fd_knlistsize)
1257 knote_fdclose(p, i);
1259 * NULL-out descriptor prior to close to avoid
1260 * a race while close blocks.
1262 fp = fdp->fd_ofiles[i];
1263 fdp->fd_ofiles[i] = NULL;
1264 fdp->fd_ofileflags[i] = 0;
1265 if (i < fdp->fd_freefile)
1266 fdp->fd_freefile = i;
1267 (void) closef(fp, td);
1270 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1275 * Close any files on exec?
1278 fdcloseexec(struct proc *p)
1280 struct thread *td = p->p_thread;
1281 struct filedesc *fdp = p->p_fd;
1284 /* Certain daemons might not have file descriptors. */
1289 * We cannot cache fd_ofiles or fd_ofileflags since operations
1290 * may block and rip them out from under us.
1292 for (i = 0; i <= fdp->fd_lastfile; i++) {
1293 if (fdp->fd_ofiles[i] != NULL &&
1294 (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1298 if (fdp->fd_ofileflags[i] & UF_MAPPED)
1299 (void) munmapfd(p, i);
1301 if (i < fdp->fd_knlistsize)
1302 knote_fdclose(p, i);
1304 * NULL-out descriptor prior to close to avoid
1305 * a race while close blocks.
1307 fp = fdp->fd_ofiles[i];
1308 fdp->fd_ofiles[i] = NULL;
1309 fdp->fd_ofileflags[i] = 0;
1310 if (i < fdp->fd_freefile)
1311 fdp->fd_freefile = i;
1312 (void) closef(fp, td);
1315 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1320 * It is unsafe for set[ug]id processes to be started with file
1321 * descriptors 0..2 closed, as these descriptors are given implicit
1322 * significance in the Standard C library. fdcheckstd() will create a
1323 * descriptor referencing /dev/null for each of stdin, stdout, and
1324 * stderr that is not already open.
1327 fdcheckstd(struct proc *p)
1329 struct thread *td = p->p_thread;
1330 struct nameidata nd;
1331 struct filedesc *fdp;
1334 int fd, i, error, flags, devnull;
1341 for (i = 0; i < 3; i++) {
1342 if (fdp->fd_ofiles[i] != NULL)
1345 error = falloc(p, &fp, &fd);
1348 NDINIT(&nd, NAMEI_LOOKUP, CNP_FOLLOW, UIO_SYSSPACE,
1350 flags = FREAD | FWRITE;
1351 error = vn_open(&nd, flags, 0);
1353 fdp->fd_ofiles[i] = NULL;
1357 NDFREE(&nd, NDF_ONLY_PNBUF);
1358 fp->f_data = (caddr_t)nd.ni_vp;
1361 fp->f_type = DTYPE_VNODE;
1362 VOP_UNLOCK(nd.ni_vp, NULL, 0, td);
1365 error = kern_dup(DUP_FIXED, devnull, i, &retval);
1374 * Internal form of close.
1375 * Decrement reference count on file structure.
1376 * Note: td and/or p may be NULL when closing a file
1377 * that was being passed in a message.
1380 closef(struct file *fp, struct thread *td)
1384 struct filedesc_to_leader *fdtol;
1391 p = NULL; /* allow no proc association */
1393 p = td->td_proc; /* can also be NULL */
1396 * POSIX record locking dictates that any close releases ALL
1397 * locks owned by this process. This is handled by setting
1398 * a flag in the unlock to free ONLY locks obeying POSIX
1399 * semantics, and not to free BSD-style file locks.
1400 * If the descriptor was in a message, POSIX-style locks
1401 * aren't passed with the descriptor.
1404 fp->f_type == DTYPE_VNODE) {
1405 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1406 lf.l_whence = SEEK_SET;
1409 lf.l_type = F_UNLCK;
1410 vp = (struct vnode *)fp->f_data;
1411 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1415 if (fdtol != NULL) {
1417 * Handle special case where file descriptor table
1418 * is shared between multiple process leaders.
1420 for (fdtol = fdtol->fdl_next;
1421 fdtol != p->p_fdtol;
1422 fdtol = fdtol->fdl_next) {
1423 if ((fdtol->fdl_leader->p_flag &
1426 fdtol->fdl_holdcount++;
1427 lf.l_whence = SEEK_SET;
1430 lf.l_type = F_UNLCK;
1431 vp = (struct vnode *)fp->f_data;
1432 (void) VOP_ADVLOCK(vp,
1433 (caddr_t)p->p_leader,
1434 F_UNLCK, &lf, F_POSIX);
1435 fdtol->fdl_holdcount--;
1436 if (fdtol->fdl_holdcount == 0 &&
1437 fdtol->fdl_wakeup != 0) {
1438 fdtol->fdl_wakeup = 0;
1444 return (fdrop(fp, td));
1448 fdrop(struct file *fp, struct thread *td)
1454 if (--fp->f_count > 0)
1456 if (fp->f_count < 0)
1457 panic("fdrop: count < 0");
1458 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1459 lf.l_whence = SEEK_SET;
1462 lf.l_type = F_UNLCK;
1463 vp = (struct vnode *)fp->f_data;
1464 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1466 if (fp->f_ops != &badfileops)
1467 error = fo_close(fp, td);
1475 * Apply an advisory lock on a file descriptor.
1477 * Just attempt to get a record lock of the requested type on
1478 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1482 flock(struct flock_args *uap)
1484 struct proc *p = curproc;
1485 struct filedesc *fdp = p->p_fd;
1490 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1491 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1493 if (fp->f_type != DTYPE_VNODE)
1494 return (EOPNOTSUPP);
1495 vp = (struct vnode *)fp->f_data;
1496 lf.l_whence = SEEK_SET;
1499 if (uap->how & LOCK_UN) {
1500 lf.l_type = F_UNLCK;
1501 fp->f_flag &= ~FHASLOCK;
1502 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1504 if (uap->how & LOCK_EX)
1505 lf.l_type = F_WRLCK;
1506 else if (uap->how & LOCK_SH)
1507 lf.l_type = F_RDLCK;
1510 fp->f_flag |= FHASLOCK;
1511 if (uap->how & LOCK_NB)
1512 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1513 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1517 * File Descriptor pseudo-device driver (/dev/fd/).
1519 * Opening minor device N dup()s the file (if any) connected to file
1520 * descriptor N belonging to the calling process. Note that this driver
1521 * consists of only the ``open()'' routine, because all subsequent
1522 * references to this file will be direct to the other driver.
1526 fdopen(dev_t dev, int mode, int type, struct thread *td)
1528 KKASSERT(td->td_proc != NULL);
1531 * XXX Kludge: set curproc->p_dupfd to contain the value of the
1532 * the file descriptor being sought for duplication. The error
1533 * return ensures that the vnode for this device will be released
1534 * by vn_open. Open will detect this special error and take the
1535 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1536 * will simply report the error.
1538 td->td_proc->p_dupfd = minor(dev);
1543 * Duplicate the specified descriptor to a free descriptor.
1546 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1552 * If the to-be-dup'd fd number is greater than the allowed number
1553 * of file descriptors, or the fd to be dup'd has already been
1554 * closed, then reject.
1556 if ((u_int)dfd >= fdp->fd_nfiles ||
1557 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
1562 * There are two cases of interest here.
1564 * For ENODEV simply dup (dfd) to file descriptor
1565 * (indx) and return.
1567 * For ENXIO steal away the file structure from (dfd) and
1568 * store it in (indx). (dfd) is effectively closed by
1571 * Any other error code is just returned.
1576 * Check that the mode the file is being opened for is a
1577 * subset of the mode of the existing descriptor.
1579 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1581 fp = fdp->fd_ofiles[indx];
1583 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1584 (void) munmapfd(p, indx);
1586 fdp->fd_ofiles[indx] = wfp;
1587 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1589 if (indx > fdp->fd_lastfile)
1590 fdp->fd_lastfile = indx;
1592 * we now own the reference to fp that the ofiles[] array
1593 * used to own. Release it.
1596 fdrop(fp, curthread);
1601 * Steal away the file pointer from dfd, and stuff it into indx.
1603 fp = fdp->fd_ofiles[indx];
1605 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1606 (void) munmapfd(p, indx);
1608 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
1609 fdp->fd_ofiles[dfd] = NULL;
1610 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1611 fdp->fd_ofileflags[dfd] = 0;
1614 * we now own the reference to fp that the ofiles[] array
1615 * used to own. Release it.
1618 fdrop(fp, curthread);
1620 * Complete the clean up of the filedesc structure by
1621 * recomputing the various hints.
1623 if (indx > fdp->fd_lastfile) {
1624 fdp->fd_lastfile = indx;
1626 while (fdp->fd_lastfile > 0 &&
1627 fdp->fd_ofiles[fdp->fd_lastfile] == NULL) {
1630 if (dfd < fdp->fd_freefile)
1631 fdp->fd_freefile = dfd;
1642 struct filedesc_to_leader *
1643 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1644 struct proc *leader)
1646 struct filedesc_to_leader *fdtol;
1648 MALLOC(fdtol, struct filedesc_to_leader *,
1649 sizeof(struct filedesc_to_leader),
1650 M_FILEDESC_TO_LEADER,
1652 fdtol->fdl_refcount = 1;
1653 fdtol->fdl_holdcount = 0;
1654 fdtol->fdl_wakeup = 0;
1655 fdtol->fdl_leader = leader;
1657 fdtol->fdl_next = old->fdl_next;
1658 fdtol->fdl_prev = old;
1659 old->fdl_next = fdtol;
1660 fdtol->fdl_next->fdl_prev = fdtol;
1662 fdtol->fdl_next = fdtol;
1663 fdtol->fdl_prev = fdtol;
1669 * Get file structures.
1672 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1679 * overestimate by 10 files
1681 return (SYSCTL_OUT(req, 0, sizeof(filehead) +
1682 (nfiles + 10) * sizeof(struct file)));
1685 error = SYSCTL_OUT(req, (caddr_t)&filehead, sizeof(filehead));
1690 * followed by an array of file structures
1692 LIST_FOREACH(fp, &filehead, f_list) {
1693 error = SYSCTL_OUT(req, (caddr_t)fp, sizeof (struct file));
1700 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1701 0, 0, sysctl_kern_file, "S,file", "Entire file table");
1703 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
1704 &maxfilesperproc, 0, "Maximum files allowed open per process");
1706 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
1707 &maxfiles, 0, "Maximum number of files");
1709 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
1710 &maxfilesrootres, 0, "Descriptors reserved for root use");
1712 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
1713 &nfiles, 0, "System-wide number of open files");
1716 fildesc_drvinit(void *unused)
1720 for (fd = 0; fd < NUMFDESC; fd++)
1721 make_dev(&fildesc_cdevsw, fd,
1722 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1723 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1724 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1725 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1728 struct fileops badfileops = {
1752 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
1758 badfo_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
1764 badfo_kqfilter(struct file *fp, struct knote *kn)
1770 badfo_stat(struct file *fp, struct stat *sb, struct thread *td)
1776 badfo_close(struct file *fp, struct thread *td)
1781 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1782 fildesc_drvinit,NULL)