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.42 2005/06/06 15:02:27 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/nlookup.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>
63 #include <sys/kcore.h>
64 #include <sys/kinfo.h>
67 #include <vm/vm_extern.h>
69 #include <sys/thread2.h>
70 #include <sys/file2.h>
72 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
73 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
74 "file desc to leader structures");
75 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
76 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
78 static d_open_t fdopen;
82 static struct cdevsw fildesc_cdevsw = {
96 /* strategy */ nostrategy,
101 static int badfo_readwrite (struct file *fp, struct uio *uio,
102 struct ucred *cred, int flags, struct thread *td);
103 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
105 static int badfo_poll (struct file *fp, int events,
106 struct ucred *cred, struct thread *td);
107 static int badfo_kqfilter (struct file *fp, struct knote *kn);
108 static int badfo_stat (struct file *fp, struct stat *sb, struct thread *td);
109 static int badfo_close (struct file *fp, struct thread *td);
112 * Descriptor management.
114 struct filelist filehead; /* head of list of open files */
115 int nfiles; /* actual number of open files */
119 * System calls on descriptors.
123 getdtablesize(struct getdtablesize_args *uap)
125 struct proc *p = curproc;
128 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
133 * Duplicate a file descriptor to a particular value.
135 * note: keep in mind that a potential race condition exists when closing
136 * descriptors from a shared descriptor table (via rfork).
140 dup2(struct dup2_args *uap)
144 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
150 * Duplicate a file descriptor.
154 dup(struct dup_args *uap)
158 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
164 kern_fcntl(int fd, int cmd, union fcntl_dat *dat)
166 struct thread *td = curthread;
167 struct proc *p = td->td_proc;
168 struct filedesc *fdp = p->p_fd;
173 int tmp, error, flg = F_POSIX;
177 if ((unsigned)fd >= fdp->fd_nfiles ||
178 (fp = fdp->fd_ofiles[fd]) == NULL)
180 pop = &fdp->fd_ofileflags[fd];
185 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
186 newmin > maxfilesperproc)
188 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
192 dat->fc_cloexec = (*pop & UF_EXCLOSE) ? FD_CLOEXEC : 0;
196 *pop = (*pop &~ UF_EXCLOSE) |
197 (dat->fc_cloexec & FD_CLOEXEC ? UF_EXCLOSE : 0);
201 dat->fc_flags = OFLAGS(fp->f_flag);
206 fp->f_flag &= ~FCNTLFLAGS;
207 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
208 tmp = fp->f_flag & FNONBLOCK;
209 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
214 tmp = fp->f_flag & FASYNC;
215 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, td);
220 fp->f_flag &= ~FNONBLOCK;
222 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, td);
228 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, td);
234 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, td);
240 /* Fall into F_SETLK */
243 if (fp->f_type != DTYPE_VNODE)
245 vp = (struct vnode *)fp->f_data;
248 * copyin/lockop may block
251 if (dat->fc_flock.l_whence == SEEK_CUR)
252 dat->fc_flock.l_start += fp->f_offset;
254 switch (dat->fc_flock.l_type) {
256 if ((fp->f_flag & FREAD) == 0) {
260 p->p_leader->p_flag |= P_ADVLOCK;
261 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
262 &dat->fc_flock, flg);
265 if ((fp->f_flag & FWRITE) == 0) {
269 p->p_leader->p_flag |= P_ADVLOCK;
270 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
271 &dat->fc_flock, flg);
274 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
275 &dat->fc_flock, F_POSIX);
281 /* Check for race with close */
282 if ((unsigned) fd >= fdp->fd_nfiles ||
283 fp != fdp->fd_ofiles[fd]) {
284 dat->fc_flock.l_whence = SEEK_SET;
285 dat->fc_flock.l_start = 0;
286 dat->fc_flock.l_len = 0;
287 dat->fc_flock.l_type = F_UNLCK;
288 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
289 F_UNLCK, &dat->fc_flock, F_POSIX);
295 if (fp->f_type != DTYPE_VNODE)
297 vp = (struct vnode *)fp->f_data;
299 * copyin/lockop may block
302 if (dat->fc_flock.l_type != F_RDLCK &&
303 dat->fc_flock.l_type != F_WRLCK &&
304 dat->fc_flock.l_type != F_UNLCK) {
308 if (dat->fc_flock.l_whence == SEEK_CUR)
309 dat->fc_flock.l_start += fp->f_offset;
310 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
311 &dat->fc_flock, F_POSIX);
321 * The file control system call.
324 fcntl(struct fcntl_args *uap)
331 dat.fc_fd = uap->arg;
334 dat.fc_cloexec = uap->arg;
337 dat.fc_flags = uap->arg;
340 dat.fc_owner = uap->arg;
345 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
346 sizeof(struct flock));
352 error = kern_fcntl(uap->fd, uap->cmd, &dat);
357 uap->sysmsg_result = dat.fc_fd;
360 uap->sysmsg_result = dat.fc_cloexec;
363 uap->sysmsg_result = dat.fc_flags;
366 uap->sysmsg_result = dat.fc_owner;
368 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
369 sizeof(struct flock));
378 * Common code for dup, dup2, and fcntl(F_DUPFD).
380 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
381 * kern_dup() to destructively dup over an existing file descriptor if new
382 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
383 * unused file descriptor that is greater than or equal to new.
386 kern_dup(enum dup_type type, int old, int new, int *res)
388 struct thread *td = curthread;
389 struct proc *p = td->td_proc;
390 struct filedesc *fdp = p->p_fd;
397 * Verify that we have a valid descriptor to dup from and
398 * possibly to dup to.
400 if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
401 new >= maxfilesperproc)
403 if (old >= fdp->fd_nfiles || fdp->fd_ofiles[old] == NULL)
405 if (type == DUP_FIXED && old == new) {
409 fp = fdp->fd_ofiles[old];
413 * Expand the table for the new descriptor if needed. This may
414 * block and drop and reacquire the fidedesc lock.
416 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
417 error = fdalloc(p, new, &newfd);
423 if (type == DUP_VARIABLE)
427 * If the old file changed out from under us then treat it as a
428 * bad file descriptor. Userland should do its own locking to
431 if (fdp->fd_ofiles[old] != fp) {
432 if (fdp->fd_ofiles[new] == NULL) {
433 if (new < fdp->fd_freefile)
434 fdp->fd_freefile = new;
435 while (fdp->fd_lastfile > 0 &&
436 fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
442 KASSERT(old != new, ("new fd is same as old"));
445 * Save info on the descriptor being overwritten. We have
446 * to do the unmap now, but we cannot close it without
447 * introducing an ownership race for the slot.
449 delfp = fdp->fd_ofiles[new];
450 if (delfp != NULL && p->p_fdtol != NULL) {
452 * Ask fdfree() to sleep to ensure that all relevant
453 * process leaders can be traversed in closef().
455 fdp->fd_holdleaderscount++;
459 KASSERT(delfp == NULL || type == DUP_FIXED,
460 ("dup() picked an open file"));
462 if (delfp && (fdp->fd_ofileflags[new] & UF_MAPPED))
463 (void) munmapfd(p, new);
467 * Duplicate the source descriptor, update lastfile
469 fdp->fd_ofiles[new] = fp;
470 fdp->fd_ofileflags[new] = fdp->fd_ofileflags[old] &~ UF_EXCLOSE;
471 if (new > fdp->fd_lastfile)
472 fdp->fd_lastfile = new;
476 * If we dup'd over a valid file, we now own the reference to it
477 * and must dispose of it using closef() semantics (as if a
478 * close() were performed on it).
481 (void) closef(delfp, td);
483 fdp->fd_holdleaderscount--;
484 if (fdp->fd_holdleaderscount == 0 &&
485 fdp->fd_holdleaderswakeup != 0) {
486 fdp->fd_holdleaderswakeup = 0;
487 wakeup(&fdp->fd_holdleaderscount);
495 * If sigio is on the list associated with a process or process group,
496 * disable signalling from the device, remove sigio from the list and
500 funsetown(struct sigio *sigio)
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(struct sigiolst *sigiolst)
524 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
529 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
531 * After permission checking, add a sigio structure to the sigio list for
532 * the process or process group.
535 fsetown(pid_t pgid, struct sigio **sigiop)
551 * Policy - Don't allow a process to FSETOWN a process
552 * in another session.
554 * Remove this test to allow maximum flexibility or
555 * restrict FSETOWN to the current process or process
556 * group for maximum safety.
558 if (proc->p_session != curproc->p_session)
562 } else /* if (pgid < 0) */ {
563 pgrp = pgfind(-pgid);
568 * Policy - Don't allow a process to FSETOWN a process
569 * in another session.
571 * Remove this test to allow maximum flexibility or
572 * restrict FSETOWN to the current process or process
573 * group for maximum safety.
575 if (pgrp->pg_session != curproc->p_session)
581 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
583 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
584 sigio->sio_proc = proc;
586 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
587 sigio->sio_pgrp = pgrp;
589 sigio->sio_pgid = pgid;
590 sigio->sio_ucred = crhold(curproc->p_ucred);
591 /* It would be convenient if p_ruid was in ucred. */
592 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
593 sigio->sio_myref = sigiop;
601 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
604 fgetown(struct sigio *sigio)
606 return (sigio != NULL ? sigio->sio_pgid : 0);
610 * Close many file descriptors.
615 closefrom(struct closefrom_args *uap)
617 return(kern_closefrom(uap->fd));
621 kern_closefrom(int fd)
623 struct thread *td = curthread;
624 struct proc *p = td->td_proc;
625 struct filedesc *fdp;
630 if (fd < 0 || fd > fdp->fd_lastfile)
634 if (kern_close(fdp->fd_lastfile) == EINTR)
636 } while (fdp->fd_lastfile > fd);
642 * Close a file descriptor.
647 close(struct close_args *uap)
649 return(kern_close(uap->fd));
655 struct thread *td = curthread;
656 struct proc *p = td->td_proc;
657 struct filedesc *fdp;
665 if ((unsigned)fd >= fdp->fd_nfiles ||
666 (fp = fdp->fd_ofiles[fd]) == NULL)
669 if (fdp->fd_ofileflags[fd] & UF_MAPPED)
670 (void) munmapfd(p, fd);
672 fdp->fd_ofiles[fd] = NULL;
673 fdp->fd_ofileflags[fd] = 0;
675 if (p->p_fdtol != NULL) {
677 * Ask fdfree() to sleep to ensure that all relevant
678 * process leaders can be traversed in closef().
680 fdp->fd_holdleaderscount++;
685 * we now hold the fp reference that used to be owned by the descriptor
688 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
690 if (fd < fdp->fd_freefile)
691 fdp->fd_freefile = fd;
692 if (fd < fdp->fd_knlistsize)
693 knote_fdclose(p, fd);
694 error = closef(fp, td);
696 fdp->fd_holdleaderscount--;
697 if (fdp->fd_holdleaderscount == 0 &&
698 fdp->fd_holdleaderswakeup != 0) {
699 fdp->fd_holdleaderswakeup = 0;
700 wakeup(&fdp->fd_holdleaderscount);
707 kern_fstat(int fd, struct stat *ub)
709 struct thread *td = curthread;
710 struct proc *p = td->td_proc;
711 struct filedesc *fdp;
718 if ((unsigned)fd >= fdp->fd_nfiles ||
719 (fp = fdp->fd_ofiles[fd]) == NULL)
722 error = fo_stat(fp, ub, td);
729 * Return status information about a file descriptor.
732 fstat(struct fstat_args *uap)
737 error = kern_fstat(uap->fd, &st);
740 error = copyout(&st, uap->sb, sizeof(st));
745 * XXX: This is for source compatibility with NetBSD. Probably doesn't
749 nfstat(struct nfstat_args *uap)
755 error = kern_fstat(uap->fd, &st);
759 error = copyout(&nst, uap->sb, sizeof (nst));
765 * Return pathconf information about a file descriptor.
769 fpathconf(struct fpathconf_args *uap)
771 struct thread *td = curthread;
772 struct proc *p = td->td_proc;
773 struct filedesc *fdp;
780 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
781 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
786 switch (fp->f_type) {
789 if (uap->name != _PC_PIPE_BUF) {
792 uap->sysmsg_result = PIPE_BUF;
798 vp = (struct vnode *)fp->f_data;
799 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
810 * Allocate a file descriptor for the process.
813 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
816 fdalloc(struct proc *p, int want, int *result)
818 struct filedesc *fdp = p->p_fd;
820 int lim, last, nfiles;
821 struct file **newofile;
825 * Search for a free descriptor starting at the higher
826 * of want or fd_freefile. If that fails, consider
827 * expanding the ofile array.
829 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
831 last = min(fdp->fd_nfiles, lim);
832 if ((i = want) < fdp->fd_freefile)
833 i = fdp->fd_freefile;
834 for (; i < last; i++) {
835 if (fdp->fd_ofiles[i] == NULL) {
836 fdp->fd_ofileflags[i] = 0;
837 if (i > fdp->fd_lastfile)
838 fdp->fd_lastfile = i;
839 if (want <= fdp->fd_freefile)
840 fdp->fd_freefile = i;
847 * No space in current array. Expand?
849 if (fdp->fd_nfiles >= lim)
851 if (fdp->fd_nfiles < NDEXTENT)
854 nfiles = 2 * fdp->fd_nfiles;
855 newofile = malloc(nfiles * OFILESIZE, M_FILEDESC, M_WAITOK);
858 * deal with file-table extend race that might have occured
859 * when malloc was blocked.
861 if (fdp->fd_nfiles >= nfiles) {
862 free(newofile, M_FILEDESC);
865 newofileflags = (char *) &newofile[nfiles];
867 * Copy the existing ofile and ofileflags arrays
868 * and zero the new portion of each array.
870 bcopy(fdp->fd_ofiles, newofile,
871 (i = sizeof(struct file *) * fdp->fd_nfiles));
872 bzero((char *)newofile + i, nfiles * sizeof(struct file *) - i);
873 bcopy(fdp->fd_ofileflags, newofileflags,
874 (i = sizeof(char) * fdp->fd_nfiles));
875 bzero(newofileflags + i, nfiles * sizeof(char) - i);
876 if (fdp->fd_nfiles > NDFILE)
877 free(fdp->fd_ofiles, M_FILEDESC);
878 fdp->fd_ofiles = newofile;
879 fdp->fd_ofileflags = newofileflags;
880 fdp->fd_nfiles = nfiles;
887 * Check to see whether n user file descriptors
888 * are available to the process p.
891 fdavail(struct proc *p, int n)
893 struct filedesc *fdp = p->p_fd;
897 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
898 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
901 last = min(fdp->fd_nfiles, lim);
902 fpp = &fdp->fd_ofiles[fdp->fd_freefile];
903 for (i = last - fdp->fd_freefile; --i >= 0; fpp++) {
904 if (*fpp == NULL && --n <= 0)
912 * Create a new open file structure and allocate a file decriptor
913 * for the process that refers to it. If p is NULL, no descriptor
914 * is allocated and the file pointer is returned unassociated with
915 * any process. resultfd is only used if p is not NULL and may
916 * separately be NULL indicating that you don't need the returned fd.
918 * A held file pointer is returned. If a descriptor has been allocated
919 * an additional hold on the fp will be made due to the fd_ofiles[]
923 falloc(struct proc *p, struct file **resultfp, int *resultfd)
925 static struct timeval lastfail;
933 * Handle filetable full issues and root overfill.
935 if (nfiles >= maxfiles - maxfilesrootres &&
936 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
937 if (ppsratecheck(&lastfail, &curfail, 1)) {
938 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
939 (p ? p->p_ucred->cr_ruid : -1));
946 * Allocate a new file descriptor.
949 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
951 fp->f_ops = &badfileops;
954 fp->f_cred = crhold(p->p_ucred);
956 fp->f_cred = crhold(proc0.p_ucred);
957 LIST_INSERT_HEAD(&filehead, fp, f_list);
959 if ((error = fsetfd(p, fp, resultfd)) != 0) {
960 fdrop(fp, p->p_thread);
972 * Associate a file pointer with a file descriptor. On success the fp
973 * will have an additional ref representing the fd_ofiles[] association.
976 fsetfd(struct proc *p, struct file *fp, int *resultfd)
984 if ((error = fdalloc(p, 0, &i)) == 0) {
986 p->p_fd->fd_ofiles[i] = fp;
993 fsetcred(struct file *fp, struct ucred *cr)
1001 * Free a file descriptor.
1004 ffree(struct file *fp)
1006 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1007 LIST_REMOVE(fp, f_list);
1010 cache_drop(fp->f_ncp);
1018 * Build a new filedesc structure.
1021 fdinit(struct proc *p)
1023 struct filedesc0 *newfdp;
1024 struct filedesc *fdp = p->p_fd;
1026 newfdp = malloc(sizeof(struct filedesc0), M_FILEDESC, M_WAITOK|M_ZERO);
1028 newfdp->fd_fd.fd_cdir = fdp->fd_cdir;
1029 vref(newfdp->fd_fd.fd_cdir);
1030 newfdp->fd_fd.fd_ncdir = cache_hold(fdp->fd_ncdir);
1034 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1035 * proc0, but should unconditionally exist in other processes.
1038 newfdp->fd_fd.fd_rdir = fdp->fd_rdir;
1039 vref(newfdp->fd_fd.fd_rdir);
1040 newfdp->fd_fd.fd_nrdir = cache_hold(fdp->fd_nrdir);
1043 newfdp->fd_fd.fd_jdir = fdp->fd_jdir;
1044 vref(newfdp->fd_fd.fd_jdir);
1045 newfdp->fd_fd.fd_njdir = cache_hold(fdp->fd_njdir);
1048 /* Create the file descriptor table. */
1049 newfdp->fd_fd.fd_refcnt = 1;
1050 newfdp->fd_fd.fd_cmask = cmask;
1051 newfdp->fd_fd.fd_ofiles = newfdp->fd_dfiles;
1052 newfdp->fd_fd.fd_ofileflags = newfdp->fd_dfileflags;
1053 newfdp->fd_fd.fd_nfiles = NDFILE;
1054 newfdp->fd_fd.fd_knlistsize = -1;
1056 return (&newfdp->fd_fd);
1060 * Share a filedesc structure.
1063 fdshare(struct proc *p)
1065 p->p_fd->fd_refcnt++;
1070 * Copy a filedesc structure.
1073 fdcopy(struct proc *p)
1075 struct filedesc *newfdp, *fdp = p->p_fd;
1079 /* Certain daemons might not have file descriptors. */
1083 newfdp = malloc(sizeof(struct filedesc0), M_FILEDESC, M_WAITOK);
1084 bcopy(fdp, newfdp, sizeof(struct filedesc));
1085 if (newfdp->fd_cdir) {
1086 vref(newfdp->fd_cdir);
1087 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1090 * We must check for fd_rdir here, at least for now because
1091 * the init process is created before we have access to the
1092 * rootvode to take a reference to it.
1094 if (newfdp->fd_rdir) {
1095 vref(newfdp->fd_rdir);
1096 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1098 if (newfdp->fd_jdir) {
1099 vref(newfdp->fd_jdir);
1100 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1102 newfdp->fd_refcnt = 1;
1105 * If the number of open files fits in the internal arrays
1106 * of the open file structure, use them, otherwise allocate
1107 * additional memory for the number of descriptors currently
1110 if (newfdp->fd_lastfile < NDFILE) {
1111 newfdp->fd_ofiles = ((struct filedesc0 *) newfdp)->fd_dfiles;
1112 newfdp->fd_ofileflags =
1113 ((struct filedesc0 *) newfdp)->fd_dfileflags;
1117 * Compute the smallest multiple of NDEXTENT needed
1118 * for the file descriptors currently in use,
1119 * allowing the table to shrink.
1121 i = newfdp->fd_nfiles;
1122 while (i > 2 * NDEXTENT && i > newfdp->fd_lastfile * 2)
1124 newfdp->fd_ofiles = malloc(i * OFILESIZE, M_FILEDESC, M_WAITOK);
1125 newfdp->fd_ofileflags = (char *) &newfdp->fd_ofiles[i];
1127 newfdp->fd_nfiles = i;
1128 bcopy(fdp->fd_ofiles, newfdp->fd_ofiles, i * sizeof(struct file **));
1129 bcopy(fdp->fd_ofileflags, newfdp->fd_ofileflags, i * sizeof(char));
1132 * kq descriptors cannot be copied.
1134 if (newfdp->fd_knlistsize != -1) {
1135 fpp = &newfdp->fd_ofiles[newfdp->fd_lastfile];
1136 for (i = newfdp->fd_lastfile; i >= 0; i--, fpp--) {
1137 if (*fpp != NULL && (*fpp)->f_type == DTYPE_KQUEUE) {
1139 if (i < newfdp->fd_freefile)
1140 newfdp->fd_freefile = i;
1142 if (*fpp == NULL && i == newfdp->fd_lastfile && i > 0)
1143 newfdp->fd_lastfile--;
1145 newfdp->fd_knlist = NULL;
1146 newfdp->fd_knlistsize = -1;
1147 newfdp->fd_knhash = NULL;
1148 newfdp->fd_knhashmask = 0;
1151 fpp = newfdp->fd_ofiles;
1152 for (i = newfdp->fd_lastfile; i-- >= 0; fpp++) {
1160 * Release a filedesc structure.
1163 fdfree(struct proc *p)
1165 struct thread *td = p->p_thread;
1166 struct filedesc *fdp = p->p_fd;
1169 struct filedesc_to_leader *fdtol;
1174 /* Certain daemons might not have file descriptors. */
1178 /* Check for special need to clear POSIX style locks */
1180 if (fdtol != NULL) {
1181 KASSERT(fdtol->fdl_refcount > 0,
1182 ("filedesc_to_refcount botch: fdl_refcount=%d",
1183 fdtol->fdl_refcount));
1184 if (fdtol->fdl_refcount == 1 &&
1185 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1187 fpp = fdp->fd_ofiles;
1188 for (i = 0, fpp = fdp->fd_ofiles;
1189 i <= fdp->fd_lastfile;
1192 (*fpp)->f_type != DTYPE_VNODE)
1196 lf.l_whence = SEEK_SET;
1199 lf.l_type = F_UNLCK;
1200 vp = (struct vnode *)fp->f_data;
1201 (void) VOP_ADVLOCK(vp,
1202 (caddr_t)p->p_leader,
1206 fdrop(fp, p->p_thread);
1207 fpp = fdp->fd_ofiles + i;
1211 if (fdtol->fdl_refcount == 1) {
1212 if (fdp->fd_holdleaderscount > 0 &&
1213 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1215 * close() or do_dup() has cleared a reference
1216 * in a shared file descriptor table.
1218 fdp->fd_holdleaderswakeup = 1;
1219 tsleep(&fdp->fd_holdleaderscount,
1223 if (fdtol->fdl_holdcount > 0) {
1225 * Ensure that fdtol->fdl_leader
1226 * remains valid in closef().
1228 fdtol->fdl_wakeup = 1;
1229 tsleep(fdtol, 0, "fdlhold", 0);
1233 fdtol->fdl_refcount--;
1234 if (fdtol->fdl_refcount == 0 &&
1235 fdtol->fdl_holdcount == 0) {
1236 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1237 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1242 free(fdtol, M_FILEDESC_TO_LEADER);
1244 if (--fdp->fd_refcnt > 0)
1247 * we are the last reference to the structure, we can
1248 * safely assume it will not change out from under us.
1250 fpp = fdp->fd_ofiles;
1251 for (i = fdp->fd_lastfile; i-- >= 0; fpp++) {
1253 (void) closef(*fpp, td);
1255 if (fdp->fd_nfiles > NDFILE)
1256 free(fdp->fd_ofiles, M_FILEDESC);
1258 cache_drop(fdp->fd_ncdir);
1259 vrele(fdp->fd_cdir);
1262 cache_drop(fdp->fd_nrdir);
1263 vrele(fdp->fd_rdir);
1266 cache_drop(fdp->fd_njdir);
1267 vrele(fdp->fd_jdir);
1270 free(fdp->fd_knlist, M_KQUEUE);
1272 free(fdp->fd_knhash, M_KQUEUE);
1273 free(fdp, M_FILEDESC);
1277 * For setugid programs, we don't want to people to use that setugidness
1278 * to generate error messages which write to a file which otherwise would
1279 * otherwise be off-limits to the process.
1281 * This is a gross hack to plug the hole. A better solution would involve
1282 * a special vop or other form of generalized access control mechanism. We
1283 * go ahead and just reject all procfs file systems accesses as dangerous.
1285 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1286 * sufficient. We also don't for check setugidness since we know we are.
1289 is_unsafe(struct file *fp)
1291 if (fp->f_type == DTYPE_VNODE &&
1292 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1298 * Make this setguid thing safe, if at all possible.
1301 setugidsafety(struct proc *p)
1303 struct thread *td = p->p_thread;
1304 struct filedesc *fdp = p->p_fd;
1307 /* Certain daemons might not have file descriptors. */
1312 * note: fdp->fd_ofiles may be reallocated out from under us while
1313 * we are blocked in a close. Be careful!
1315 for (i = 0; i <= fdp->fd_lastfile; i++) {
1318 if (fdp->fd_ofiles[i] && is_unsafe(fdp->fd_ofiles[i])) {
1322 if ((fdp->fd_ofileflags[i] & UF_MAPPED) != 0)
1323 (void) munmapfd(p, i);
1325 if (i < fdp->fd_knlistsize)
1326 knote_fdclose(p, i);
1328 * NULL-out descriptor prior to close to avoid
1329 * a race while close blocks.
1331 fp = fdp->fd_ofiles[i];
1332 fdp->fd_ofiles[i] = NULL;
1333 fdp->fd_ofileflags[i] = 0;
1334 if (i < fdp->fd_freefile)
1335 fdp->fd_freefile = i;
1336 (void) closef(fp, td);
1339 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1344 * Close any files on exec?
1347 fdcloseexec(struct proc *p)
1349 struct thread *td = p->p_thread;
1350 struct filedesc *fdp = p->p_fd;
1353 /* Certain daemons might not have file descriptors. */
1358 * We cannot cache fd_ofiles or fd_ofileflags since operations
1359 * may block and rip them out from under us.
1361 for (i = 0; i <= fdp->fd_lastfile; i++) {
1362 if (fdp->fd_ofiles[i] != NULL &&
1363 (fdp->fd_ofileflags[i] & UF_EXCLOSE)) {
1367 if (fdp->fd_ofileflags[i] & UF_MAPPED)
1368 (void) munmapfd(p, i);
1370 if (i < fdp->fd_knlistsize)
1371 knote_fdclose(p, i);
1373 * NULL-out descriptor prior to close to avoid
1374 * a race while close blocks.
1376 fp = fdp->fd_ofiles[i];
1377 fdp->fd_ofiles[i] = NULL;
1378 fdp->fd_ofileflags[i] = 0;
1379 if (i < fdp->fd_freefile)
1380 fdp->fd_freefile = i;
1381 (void) closef(fp, td);
1384 while (fdp->fd_lastfile > 0 && fdp->fd_ofiles[fdp->fd_lastfile] == NULL)
1389 * It is unsafe for set[ug]id processes to be started with file
1390 * descriptors 0..2 closed, as these descriptors are given implicit
1391 * significance in the Standard C library. fdcheckstd() will create a
1392 * descriptor referencing /dev/null for each of stdin, stdout, and
1393 * stderr that is not already open.
1396 fdcheckstd(struct proc *p)
1398 struct thread *td = p->p_thread;
1399 struct nlookupdata nd;
1400 struct filedesc *fdp;
1403 int fd, i, error, flags, devnull;
1410 for (i = 0; i < 3; i++) {
1411 if (fdp->fd_ofiles[i] != NULL)
1414 if ((error = falloc(p, &fp, NULL)) != 0)
1417 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1418 NLC_FOLLOW|NLC_LOCKVP);
1419 flags = FREAD | FWRITE;
1421 error = vn_open(&nd, fp, flags, 0);
1423 error = fsetfd(p, fp, &fd);
1431 error = kern_dup(DUP_FIXED, devnull, i, &retval);
1440 * Internal form of close.
1441 * Decrement reference count on file structure.
1442 * Note: td and/or p may be NULL when closing a file
1443 * that was being passed in a message.
1446 closef(struct file *fp, struct thread *td)
1450 struct filedesc_to_leader *fdtol;
1457 p = NULL; /* allow no proc association */
1459 p = td->td_proc; /* can also be NULL */
1462 * POSIX record locking dictates that any close releases ALL
1463 * locks owned by this process. This is handled by setting
1464 * a flag in the unlock to free ONLY locks obeying POSIX
1465 * semantics, and not to free BSD-style file locks.
1466 * If the descriptor was in a message, POSIX-style locks
1467 * aren't passed with the descriptor.
1470 fp->f_type == DTYPE_VNODE) {
1471 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1472 lf.l_whence = SEEK_SET;
1475 lf.l_type = F_UNLCK;
1476 vp = (struct vnode *)fp->f_data;
1477 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1481 if (fdtol != NULL) {
1483 * Handle special case where file descriptor table
1484 * is shared between multiple process leaders.
1486 for (fdtol = fdtol->fdl_next;
1487 fdtol != p->p_fdtol;
1488 fdtol = fdtol->fdl_next) {
1489 if ((fdtol->fdl_leader->p_flag &
1492 fdtol->fdl_holdcount++;
1493 lf.l_whence = SEEK_SET;
1496 lf.l_type = F_UNLCK;
1497 vp = (struct vnode *)fp->f_data;
1498 (void) VOP_ADVLOCK(vp,
1499 (caddr_t)p->p_leader,
1500 F_UNLCK, &lf, F_POSIX);
1501 fdtol->fdl_holdcount--;
1502 if (fdtol->fdl_holdcount == 0 &&
1503 fdtol->fdl_wakeup != 0) {
1504 fdtol->fdl_wakeup = 0;
1510 return (fdrop(fp, td));
1514 fdrop(struct file *fp, struct thread *td)
1520 if (--fp->f_count > 0)
1522 if (fp->f_count < 0)
1523 panic("fdrop: count < 0");
1524 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1525 lf.l_whence = SEEK_SET;
1528 lf.l_type = F_UNLCK;
1529 vp = (struct vnode *)fp->f_data;
1530 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
1532 if (fp->f_ops != &badfileops)
1533 error = fo_close(fp, td);
1541 * Apply an advisory lock on a file descriptor.
1543 * Just attempt to get a record lock of the requested type on
1544 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1548 flock(struct flock_args *uap)
1550 struct proc *p = curproc;
1551 struct filedesc *fdp = p->p_fd;
1556 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1557 (fp = fdp->fd_ofiles[uap->fd]) == NULL)
1559 if (fp->f_type != DTYPE_VNODE)
1560 return (EOPNOTSUPP);
1561 vp = (struct vnode *)fp->f_data;
1562 lf.l_whence = SEEK_SET;
1565 if (uap->how & LOCK_UN) {
1566 lf.l_type = F_UNLCK;
1567 fp->f_flag &= ~FHASLOCK;
1568 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK));
1570 if (uap->how & LOCK_EX)
1571 lf.l_type = F_WRLCK;
1572 else if (uap->how & LOCK_SH)
1573 lf.l_type = F_RDLCK;
1576 fp->f_flag |= FHASLOCK;
1577 if (uap->how & LOCK_NB)
1578 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK));
1579 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_FLOCK|F_WAIT));
1583 * File Descriptor pseudo-device driver (/dev/fd/).
1585 * Opening minor device N dup()s the file (if any) connected to file
1586 * descriptor N belonging to the calling process. Note that this driver
1587 * consists of only the ``open()'' routine, because all subsequent
1588 * references to this file will be direct to the other driver.
1592 fdopen(dev_t dev, int mode, int type, struct thread *td)
1594 KKASSERT(td->td_proc != NULL);
1597 * XXX Kludge: set curproc->p_dupfd to contain the value of the
1598 * the file descriptor being sought for duplication. The error
1599 * return ensures that the vnode for this device will be released
1600 * by vn_open. Open will detect this special error and take the
1601 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1602 * will simply report the error.
1604 td->td_proc->p_dupfd = minor(dev);
1609 * Duplicate the specified descriptor to a free descriptor.
1612 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1618 * If the to-be-dup'd fd number is greater than the allowed number
1619 * of file descriptors, or the fd to be dup'd has already been
1620 * closed, then reject.
1622 if ((u_int)dfd >= fdp->fd_nfiles ||
1623 (wfp = fdp->fd_ofiles[dfd]) == NULL) {
1628 * There are two cases of interest here.
1630 * For ENODEV simply dup (dfd) to file descriptor
1631 * (indx) and return.
1633 * For ENXIO steal away the file structure from (dfd) and
1634 * store it in (indx). (dfd) is effectively closed by
1637 * Any other error code is just returned.
1642 * Check that the mode the file is being opened for is a
1643 * subset of the mode of the existing descriptor.
1645 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1647 fp = fdp->fd_ofiles[indx];
1649 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1650 (void) munmapfd(p, indx);
1652 fdp->fd_ofiles[indx] = wfp;
1653 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1655 if (indx > fdp->fd_lastfile)
1656 fdp->fd_lastfile = indx;
1658 * we now own the reference to fp that the ofiles[] array
1659 * used to own. Release it.
1662 fdrop(fp, curthread);
1667 * Steal away the file pointer from dfd, and stuff it into indx.
1669 fp = fdp->fd_ofiles[indx];
1671 if (fp && fdp->fd_ofileflags[indx] & UF_MAPPED)
1672 (void) munmapfd(p, indx);
1674 fdp->fd_ofiles[indx] = fdp->fd_ofiles[dfd];
1675 fdp->fd_ofiles[dfd] = NULL;
1676 fdp->fd_ofileflags[indx] = fdp->fd_ofileflags[dfd];
1677 fdp->fd_ofileflags[dfd] = 0;
1680 * we now own the reference to fp that the ofiles[] array
1681 * used to own. Release it.
1684 fdrop(fp, curthread);
1686 * Complete the clean up of the filedesc structure by
1687 * recomputing the various hints.
1689 if (indx > fdp->fd_lastfile) {
1690 fdp->fd_lastfile = indx;
1692 while (fdp->fd_lastfile > 0 &&
1693 fdp->fd_ofiles[fdp->fd_lastfile] == NULL) {
1696 if (dfd < fdp->fd_freefile)
1697 fdp->fd_freefile = dfd;
1708 struct filedesc_to_leader *
1709 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
1710 struct proc *leader)
1712 struct filedesc_to_leader *fdtol;
1714 fdtol = malloc(sizeof(struct filedesc_to_leader),
1715 M_FILEDESC_TO_LEADER, M_WAITOK);
1716 fdtol->fdl_refcount = 1;
1717 fdtol->fdl_holdcount = 0;
1718 fdtol->fdl_wakeup = 0;
1719 fdtol->fdl_leader = leader;
1721 fdtol->fdl_next = old->fdl_next;
1722 fdtol->fdl_prev = old;
1723 old->fdl_next = fdtol;
1724 fdtol->fdl_next->fdl_prev = fdtol;
1726 fdtol->fdl_next = fdtol;
1727 fdtol->fdl_prev = fdtol;
1733 * Get file structures.
1736 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
1738 struct kinfo_file kf;
1739 struct filedesc *fdp;
1747 * Note: because the number of file descriptors is calculated
1748 * in different ways for sizing vs returning the data,
1749 * there is information leakage from the first loop. However,
1750 * it is of a similar order of magnitude to the leakage from
1751 * global system statistics such as kern.openfiles.
1753 * When just doing a count, note that we cannot just count
1754 * the elements and add f_count via the filehead list because
1755 * threaded processes share their descriptor table and f_count might
1756 * still be '1' in that case.
1760 LIST_FOREACH(p, &allproc, p_list) {
1761 if (p->p_stat == SIDL)
1763 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
1765 if ((fdp = p->p_fd) == NULL)
1767 for (n = 0; n < fdp->fd_nfiles; ++n) {
1768 if ((fp = fdp->fd_ofiles[n]) == NULL)
1770 if (req->oldptr == NULL) {
1773 kcore_make_file(&kf, fp, p->p_pid,
1774 p->p_ucred->cr_uid, n);
1775 error = SYSCTL_OUT(req, &kf, sizeof(kf));
1785 * When just calculating the size, overestimate a bit to try to
1786 * prevent system activity from causing the buffer-fill call
1789 if (req->oldptr == NULL) {
1790 count = (count + 16) + (count / 10);
1791 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
1796 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
1797 0, 0, sysctl_kern_file, "S,file", "Entire file table");
1799 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
1800 &maxfilesperproc, 0, "Maximum files allowed open per process");
1802 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
1803 &maxfiles, 0, "Maximum number of files");
1805 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
1806 &maxfilesrootres, 0, "Descriptors reserved for root use");
1808 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
1809 &nfiles, 0, "System-wide number of open files");
1812 fildesc_drvinit(void *unused)
1816 cdevsw_add(&fildesc_cdevsw, 0, 0);
1817 for (fd = 0; fd < NUMFDESC; fd++) {
1818 make_dev(&fildesc_cdevsw, fd,
1819 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
1821 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
1822 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
1823 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
1826 struct fileops badfileops = {
1850 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct thread *td)
1856 badfo_poll(struct file *fp, int events, struct ucred *cred, struct thread *td)
1862 badfo_kqfilter(struct file *fp, struct knote *kn)
1868 badfo_stat(struct file *fp, struct stat *sb, struct thread *td)
1874 badfo_close(struct file *fp, struct thread *td)
1879 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
1880 fildesc_drvinit,NULL)