2 * Copyright (c) 2005 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1989, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 * (c) UNIX System Laboratories, Inc.
38 * All or some portions of this file are derived from material licensed
39 * to the University of California by American Telephone and Telegraph
40 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41 * the permission of UNIX System Laboratories, Inc.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
72 * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.19 2004/02/28 00:43:31 tegge Exp $
73 * $DragonFly: src/sys/kern/kern_descrip.c,v 1.61 2006/05/22 21:33:11 dillon Exp $
76 #include "opt_compat.h"
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/malloc.h>
80 #include <sys/sysproto.h>
82 #include <sys/filedesc.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
85 #include <sys/vnode.h>
87 #include <sys/nlookup.h>
90 #include <sys/filio.h>
91 #include <sys/fcntl.h>
92 #include <sys/unistd.h>
93 #include <sys/resourcevar.h>
94 #include <sys/event.h>
95 #include <sys/kern_syscall.h>
96 #include <sys/kcore.h>
97 #include <sys/kinfo.h>
100 #include <vm/vm_extern.h>
102 #include <sys/thread2.h>
103 #include <sys/file2.h>
104 #include <sys/spinlock2.h>
106 static void fdreserve (struct filedesc *fdp, int fd0, int incr);
107 static struct file *funsetfd (struct filedesc *fdp, int fd);
108 static int checkfpclosed(struct filedesc *fdp, int fd, struct file *fp);
110 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
111 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
112 "file desc to leader structures");
113 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
114 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
116 static d_open_t fdopen;
119 #define CDEV_MAJOR 22
120 static struct cdevsw fildesc_cdevsw = {
122 /* maj */ CDEV_MAJOR,
134 /* strategy */ nostrategy,
139 static int badfo_readwrite (struct file *fp, struct uio *uio,
140 struct ucred *cred, int flags);
141 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
143 static int badfo_poll (struct file *fp, int events, struct ucred *cred);
144 static int badfo_kqfilter (struct file *fp, struct knote *kn);
145 static int badfo_stat (struct file *fp, struct stat *sb, struct ucred *cred);
146 static int badfo_close (struct file *fp);
147 static int badfo_shutdown (struct file *fp, int how);
150 * Descriptor management.
152 struct filelist filehead; /* head of list of open files */
153 int nfiles; /* actual number of open files */
157 * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
161 fdfixup(struct filedesc *fdp, int fd)
163 if (fd < fdp->fd_freefile) {
164 fdp->fd_freefile = fd;
166 while (fdp->fd_lastfile >= 0 &&
167 fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
168 fdp->fd_files[fdp->fd_lastfile].reserved == 0
175 * System calls on descriptors.
179 getdtablesize(struct getdtablesize_args *uap)
181 struct proc *p = curproc;
184 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
189 * Duplicate a file descriptor to a particular value.
191 * note: keep in mind that a potential race condition exists when closing
192 * descriptors from a shared descriptor table (via rfork).
196 dup2(struct dup2_args *uap)
200 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
206 * Duplicate a file descriptor.
210 dup(struct dup_args *uap)
214 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
220 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
222 struct thread *td = curthread;
223 struct proc *p = td->td_proc;
227 int tmp, error, flg = F_POSIX;
231 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
237 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
238 newmin > maxfilesperproc) {
242 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
246 error = fgetfdflags(p->p_fd, fd, &tmp);
248 dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
252 if (dat->fc_cloexec & FD_CLOEXEC)
253 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
255 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
259 dat->fc_flags = OFLAGS(fp->f_flag);
264 fp->f_flag &= ~FCNTLFLAGS;
265 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
266 tmp = fp->f_flag & FNONBLOCK;
267 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
270 tmp = fp->f_flag & FASYNC;
271 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
274 fp->f_flag &= ~FNONBLOCK;
276 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
280 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
284 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
289 /* Fall into F_SETLK */
292 if (fp->f_type != DTYPE_VNODE) {
296 vp = (struct vnode *)fp->f_data;
299 * copyin/lockop may block
301 if (dat->fc_flock.l_whence == SEEK_CUR)
302 dat->fc_flock.l_start += fp->f_offset;
304 switch (dat->fc_flock.l_type) {
306 if ((fp->f_flag & FREAD) == 0) {
310 p->p_leader->p_flag |= P_ADVLOCK;
311 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
312 &dat->fc_flock, flg);
315 if ((fp->f_flag & FWRITE) == 0) {
319 p->p_leader->p_flag |= P_ADVLOCK;
320 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
321 &dat->fc_flock, flg);
324 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
325 &dat->fc_flock, F_POSIX);
333 * It is possible to race a close() on the descriptor while
334 * we were blocked getting the lock. If this occurs the
335 * close might not have caught the lock.
337 if (checkfpclosed(p->p_fd, fd, fp)) {
338 dat->fc_flock.l_whence = SEEK_SET;
339 dat->fc_flock.l_start = 0;
340 dat->fc_flock.l_len = 0;
341 dat->fc_flock.l_type = F_UNLCK;
342 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
343 F_UNLCK, &dat->fc_flock, F_POSIX);
348 if (fp->f_type != DTYPE_VNODE) {
352 vp = (struct vnode *)fp->f_data;
354 * copyin/lockop may block
356 if (dat->fc_flock.l_type != F_RDLCK &&
357 dat->fc_flock.l_type != F_WRLCK &&
358 dat->fc_flock.l_type != F_UNLCK) {
362 if (dat->fc_flock.l_whence == SEEK_CUR)
363 dat->fc_flock.l_start += fp->f_offset;
364 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
365 &dat->fc_flock, F_POSIX);
376 * The file control system call.
379 fcntl(struct fcntl_args *uap)
386 dat.fc_fd = uap->arg;
389 dat.fc_cloexec = uap->arg;
392 dat.fc_flags = uap->arg;
395 dat.fc_owner = uap->arg;
400 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
401 sizeof(struct flock));
407 error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
412 uap->sysmsg_result = dat.fc_fd;
415 uap->sysmsg_result = dat.fc_cloexec;
418 uap->sysmsg_result = dat.fc_flags;
421 uap->sysmsg_result = dat.fc_owner;
423 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
424 sizeof(struct flock));
433 * Common code for dup, dup2, and fcntl(F_DUPFD).
435 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
436 * kern_dup() to destructively dup over an existing file descriptor if new
437 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
438 * unused file descriptor that is greater than or equal to new.
441 kern_dup(enum dup_type type, int old, int new, int *res)
443 struct thread *td = curthread;
444 struct proc *p = td->td_proc;
445 struct filedesc *fdp = p->p_fd;
453 * Verify that we have a valid descriptor to dup from and
454 * possibly to dup to.
457 if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
458 new >= maxfilesperproc)
460 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL)
462 if (type == DUP_FIXED && old == new) {
466 fp = fdp->fd_files[old].fp;
467 oldflags = fdp->fd_files[old].fileflags;
471 * Allocate a new descriptor if DUP_VARIABLE, or expand the table
472 * if the requested descriptor is beyond the current table size.
474 * This can block. Retry if the source descriptor no longer matches
475 * or if our expectation in the expansion case races.
477 * If we are not expanding or allocating a new decriptor, then reset
478 * the target descriptor to a reserved state so we have a uniform
479 * setup for the next code block.
481 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
482 error = fdalloc(p, new, &newfd);
487 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
488 fsetfd(p, NULL, newfd);
492 if (type != DUP_VARIABLE && new != newfd) {
493 fsetfd(p, NULL, newfd);
498 fsetfd(p, NULL, newfd);
505 if (fdp->fd_files[new].reserved) {
507 printf("Warning: dup(): target descriptor %d is reserved, waiting for it to be resolved\n", new);
508 tsleep(fdp, 0, "fdres", hz);
513 * If the target descriptor was never allocated we have
514 * to allocate it. If it was we have to clean out the
517 delfp = fdp->fd_files[new].fp;
518 fdp->fd_files[new].fp = NULL;
519 fdp->fd_files[new].reserved = 1;
521 fdreserve(fdp, new, 1);
522 if (new > fdp->fd_lastfile)
523 fdp->fd_lastfile = new;
529 * If a descriptor is being overwritten we may hve to tell
530 * fdfree() to sleep to ensure that all relevant process
531 * leaders can be traversed in closef().
533 if (delfp != NULL && p->p_fdtol != NULL) {
534 fdp->fd_holdleaderscount++;
539 KASSERT(delfp == NULL || type == DUP_FIXED,
540 ("dup() picked an open file"));
543 * Duplicate the source descriptor, update lastfile. If the new
544 * descriptor was not allocated and we aren't replacing an existing
545 * descriptor we have to mark the descriptor as being in use.
547 * The fd_files[] array inherits fp's hold reference.
551 fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
555 * If we dup'd over a valid file, we now own the reference to it
556 * and must dispose of it using closef() semantics (as if a
557 * close() were performed on it).
560 (void) closef(delfp, td);
562 fdp->fd_holdleaderscount--;
563 if (fdp->fd_holdleaderscount == 0 &&
564 fdp->fd_holdleaderswakeup != 0) {
565 fdp->fd_holdleaderswakeup = 0;
566 wakeup(&fdp->fd_holdleaderscount);
574 * If sigio is on the list associated with a process or process group,
575 * disable signalling from the device, remove sigio from the list and
579 funsetown(struct sigio *sigio)
584 *(sigio->sio_myref) = NULL;
586 if (sigio->sio_pgid < 0) {
587 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
589 } else /* if ((*sigiop)->sio_pgid > 0) */ {
590 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
593 crfree(sigio->sio_ucred);
594 free(sigio, M_SIGIO);
597 /* Free a list of sigio structures. */
599 funsetownlst(struct sigiolst *sigiolst)
603 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
608 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
610 * After permission checking, add a sigio structure to the sigio list for
611 * the process or process group.
614 fsetown(pid_t pgid, struct sigio **sigiop)
630 * Policy - Don't allow a process to FSETOWN a process
631 * in another session.
633 * Remove this test to allow maximum flexibility or
634 * restrict FSETOWN to the current process or process
635 * group for maximum safety.
637 if (proc->p_session != curproc->p_session)
641 } else /* if (pgid < 0) */ {
642 pgrp = pgfind(-pgid);
647 * Policy - Don't allow a process to FSETOWN a process
648 * in another session.
650 * Remove this test to allow maximum flexibility or
651 * restrict FSETOWN to the current process or process
652 * group for maximum safety.
654 if (pgrp->pg_session != curproc->p_session)
660 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
662 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
663 sigio->sio_proc = proc;
665 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
666 sigio->sio_pgrp = pgrp;
668 sigio->sio_pgid = pgid;
669 sigio->sio_ucred = crhold(curproc->p_ucred);
670 /* It would be convenient if p_ruid was in ucred. */
671 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
672 sigio->sio_myref = sigiop;
680 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
683 fgetown(struct sigio *sigio)
685 return (sigio != NULL ? sigio->sio_pgid : 0);
689 * Close many file descriptors.
694 closefrom(struct closefrom_args *uap)
696 return(kern_closefrom(uap->fd));
700 kern_closefrom(int fd)
702 struct thread *td = curthread;
703 struct proc *p = td->td_proc;
704 struct filedesc *fdp;
709 if ((unsigned)fd > fdp->fd_lastfile)
713 * NOTE: This function will skip unassociated descriptors and
714 * reserved descriptors that have not yet been assigned.
715 * fd_lastfile can change as a side effect of kern_close().
717 while (fd <= fdp->fd_lastfile) {
718 if (fdp->fd_files[fd].fp != NULL) {
719 if (kern_close(fd) == EINTR)
728 * Close a file descriptor.
733 close(struct close_args *uap)
735 return(kern_close(uap->fd));
741 struct thread *td = curthread;
742 struct proc *p = td->td_proc;
743 struct filedesc *fdp;
751 if ((fp = funsetfd(fdp, fd)) == NULL)
754 if (p->p_fdtol != NULL) {
756 * Ask fdfree() to sleep to ensure that all relevant
757 * process leaders can be traversed in closef().
759 fdp->fd_holdleaderscount++;
764 * we now hold the fp reference that used to be owned by the descriptor
767 if (fd < fdp->fd_knlistsize)
768 knote_fdclose(p, fd);
769 error = closef(fp, td);
771 fdp->fd_holdleaderscount--;
772 if (fdp->fd_holdleaderscount == 0 &&
773 fdp->fd_holdleaderswakeup != 0) {
774 fdp->fd_holdleaderswakeup = 0;
775 wakeup(&fdp->fd_holdleaderscount);
782 * shutdown_args(int fd, int how)
785 kern_shutdown(int fd, int how)
787 struct thread *td = curthread;
788 struct proc *p = td->td_proc;
789 struct filedesc *fdp;
796 if ((unsigned)fd >= fdp->fd_nfiles ||
797 (fp = fdp->fd_files[fd].fp) == NULL)
800 error = fo_shutdown(fp, how);
807 shutdown(struct shutdown_args *uap)
811 error = kern_shutdown(uap->s, uap->how);
817 kern_fstat(int fd, struct stat *ub)
819 struct thread *td = curthread;
820 struct proc *p = td->td_proc;
821 struct filedesc *fdp;
828 if ((unsigned)fd >= fdp->fd_nfiles ||
829 (fp = fdp->fd_files[fd].fp) == NULL)
832 error = fo_stat(fp, ub, p->p_ucred);
839 * Return status information about a file descriptor.
842 fstat(struct fstat_args *uap)
847 error = kern_fstat(uap->fd, &st);
850 error = copyout(&st, uap->sb, sizeof(st));
855 * Return pathconf information about a file descriptor.
859 fpathconf(struct fpathconf_args *uap)
861 struct thread *td = curthread;
862 struct proc *p = td->td_proc;
863 struct filedesc *fdp;
870 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
871 (fp = fdp->fd_files[uap->fd].fp) == NULL)
876 switch (fp->f_type) {
879 if (uap->name != _PC_PIPE_BUF) {
882 uap->sysmsg_result = PIPE_BUF;
888 vp = (struct vnode *)fp->f_data;
889 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
900 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
903 fdgrow(struct filedesc *fdp, int want)
905 struct fdnode *newfiles;
906 struct fdnode *oldfiles;
911 /* nf has to be of the form 2^n - 1 */
913 } while (nf <= want);
915 newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
918 * deal with file-table extend race that might have occured
919 * when malloc was blocked.
921 if (fdp->fd_nfiles >= nf) {
922 free(newfiles, M_FILEDESC);
926 * Copy the existing ofile and ofileflags arrays
927 * and zero the new portion of each array.
929 extra = nf - fdp->fd_nfiles;
930 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
931 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
933 oldfiles = fdp->fd_files;
934 fdp->fd_files = newfiles;
937 if (oldfiles != fdp->fd_builtin_files)
938 free(oldfiles, M_FILEDESC);
943 * Number of nodes in right subtree, including the root.
946 right_subtree_size(int n)
948 return (n ^ (n | (n + 1)));
955 right_ancestor(int n)
957 return (n | (n + 1));
966 return ((n & (n + 1)) - 1);
971 fdreserve(struct filedesc *fdp, int fd, int incr)
974 fdp->fd_files[fd].allocated += incr;
975 KKASSERT(fdp->fd_files[fd].allocated >= 0);
976 fd = left_ancestor(fd);
981 * Reserve a file descriptor for the process. If no error occurs, the
982 * caller MUST at some point call fsetfd() or assign a file pointer
983 * or dispose of the reservation.
986 fdalloc(struct proc *p, int want, int *result)
988 struct filedesc *fdp = p->p_fd;
989 int fd, rsize, rsum, node, lim;
991 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
994 if (want >= fdp->fd_nfiles)
998 * Search for a free descriptor starting at the higher
999 * of want or fd_freefile. If that fails, consider
1000 * expanding the ofile array.
1002 * NOTE! the 'allocated' field is a cumulative recursive allocation
1003 * count. If we happen to see a value of 0 then we can shortcut
1004 * our search. Otherwise we run through through the tree going
1005 * down branches we know have free descriptor(s) until we hit a
1006 * leaf node. The leaf node will be free but will not necessarily
1007 * have an allocated field of 0.
1010 /* move up the tree looking for a subtree with a free node */
1011 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1012 fd = right_ancestor(fd)) {
1013 if (fdp->fd_files[fd].allocated == 0)
1016 rsize = right_subtree_size(fd);
1017 if (fdp->fd_files[fd].allocated == rsize)
1018 continue; /* right subtree full */
1021 * Free fd is in the right subtree of the tree rooted at fd.
1022 * Call that subtree R. Look for the smallest (leftmost)
1023 * subtree of R with an unallocated fd: continue moving
1024 * down the left branch until encountering a full left
1025 * subtree, then move to the right.
1027 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1029 rsum += fdp->fd_files[node].allocated;
1030 if (fdp->fd_files[fd].allocated == rsum + rsize) {
1031 fd = node; /* move to the right */
1032 if (fdp->fd_files[node].allocated == 0)
1041 * No space in current array. Expand?
1043 if (fdp->fd_nfiles >= lim)
1049 KKASSERT(fd < fdp->fd_nfiles);
1050 if (fd > fdp->fd_lastfile)
1051 fdp->fd_lastfile = fd;
1052 if (want <= fdp->fd_freefile)
1053 fdp->fd_freefile = fd;
1055 KKASSERT(fdp->fd_files[fd].fp == NULL);
1056 KKASSERT(fdp->fd_files[fd].reserved == 0);
1057 fdp->fd_files[fd].fileflags = 0;
1058 fdp->fd_files[fd].reserved = 1;
1059 fdreserve(fdp, fd, 1);
1064 * Check to see whether n user file descriptors
1065 * are available to the process p.
1068 fdavail(struct proc *p, int n)
1070 struct filedesc *fdp = p->p_fd;
1071 struct fdnode *fdnode;
1074 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1075 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1078 last = min(fdp->fd_nfiles, lim);
1079 fdnode = &fdp->fd_files[fdp->fd_freefile];
1080 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1081 if (fdnode->fp == NULL && --n <= 0)
1089 * Create a new open file structure and reserve a file decriptor
1090 * for the process that refers to it.
1092 * Root creds are checked using p, or assumed if p is NULL. If
1093 * resultfd is non-NULL then p must also be non-NULL. No file
1094 * descriptor is reserved if resultfd is NULL.
1096 * A file pointer with a refcount of 1 is returned. Note that the
1097 * file pointer is NOT associated with the descriptor. If falloc
1098 * returns success, fsetfd() MUST be called to either associate the
1099 * file pointer or clear the reservation.
1102 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1104 static struct timeval lastfail;
1112 * Handle filetable full issues and root overfill.
1114 if (nfiles >= maxfiles - maxfilesrootres &&
1115 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1116 if (ppsratecheck(&lastfail, &curfail, 1)) {
1117 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1118 (p ? p->p_ucred->cr_ruid : -1));
1125 * Allocate a new file descriptor.
1128 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1129 spin_init(&fp->f_spin);
1131 fp->f_ops = &badfileops;
1134 fp->f_cred = crhold(p->p_ucred);
1136 fp->f_cred = crhold(proc0.p_ucred);
1137 LIST_INSERT_HEAD(&filehead, fp, f_list);
1139 if ((error = fdalloc(p, 0, resultfd)) != 0) {
1156 checkfpclosed(struct filedesc *fdp, int fd, struct file *fp)
1160 spin_lock_rd(&fdp->fd_spin);
1161 if ((unsigned) fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1165 spin_unlock_rd(&fdp->fd_spin);
1170 * Associate a file pointer with a previously reserved file descriptor.
1171 * This function always succeeds.
1173 * If fp is NULL, the file descriptor is returned to the pool.
1176 fsetfd(struct proc *p, struct file *fp, int fd)
1178 struct filedesc *fdp = p->p_fd;
1180 KKASSERT((unsigned)fd < fdp->fd_nfiles);
1181 KKASSERT(fdp->fd_files[fd].reserved != 0);
1184 fdp->fd_files[fd].fp = fp;
1185 fdp->fd_files[fd].reserved = 0;
1187 fdp->fd_files[fd].reserved = 0;
1188 fdreserve(fdp, fd, -1);
1195 funsetfd(struct filedesc *fdp, int fd)
1199 if ((unsigned)fd >= fdp->fd_nfiles)
1201 if ((fp = fdp->fd_files[fd].fp) == NULL)
1203 fdp->fd_files[fd].fp = NULL;
1204 fdp->fd_files[fd].fileflags = 0;
1206 fdreserve(fdp, fd, -1);
1215 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1219 spin_lock_rd(&fdp->fd_spin);
1220 if (((u_int)fd) >= fdp->fd_nfiles) {
1222 } else if (fdp->fd_files[fd].fp == NULL) {
1225 *flagsp = fdp->fd_files[fd].fileflags;
1228 spin_unlock_rd(&fdp->fd_spin);
1236 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1240 spin_lock_wr(&fdp->fd_spin);
1241 if (((u_int)fd) >= fdp->fd_nfiles) {
1243 } else if (fdp->fd_files[fd].fp == NULL) {
1246 fdp->fd_files[fd].fileflags |= add_flags;
1249 spin_unlock_wr(&fdp->fd_spin);
1257 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1261 spin_lock_wr(&fdp->fd_spin);
1262 if (((u_int)fd) >= fdp->fd_nfiles) {
1264 } else if (fdp->fd_files[fd].fp == NULL) {
1267 fdp->fd_files[fd].fileflags &= ~rem_flags;
1270 spin_unlock_wr(&fdp->fd_spin);
1275 fsetcred(struct file *fp, struct ucred *cr)
1283 * Free a file descriptor.
1286 ffree(struct file *fp)
1288 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1289 LIST_REMOVE(fp, f_list);
1292 cache_drop(fp->f_ncp);
1300 * called from init_main, initialize filedesc0 for proc0.
1303 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1307 fdp0->fd_refcnt = 1;
1308 fdp0->fd_cmask = cmask;
1309 fdp0->fd_files = fdp0->fd_builtin_files;
1310 fdp0->fd_nfiles = NDFILE;
1311 fdp0->fd_lastfile = -1;
1312 spin_init(&fdp0->fd_spin);
1316 * Build a new filedesc structure.
1319 fdinit(struct proc *p)
1321 struct filedesc *newfdp;
1322 struct filedesc *fdp = p->p_fd;
1324 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1326 newfdp->fd_cdir = fdp->fd_cdir;
1327 vref(newfdp->fd_cdir);
1328 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1332 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1333 * proc0, but should unconditionally exist in other processes.
1336 newfdp->fd_rdir = fdp->fd_rdir;
1337 vref(newfdp->fd_rdir);
1338 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1341 newfdp->fd_jdir = fdp->fd_jdir;
1342 vref(newfdp->fd_jdir);
1343 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1346 /* Create the file descriptor table. */
1347 newfdp->fd_refcnt = 1;
1348 newfdp->fd_cmask = cmask;
1349 newfdp->fd_files = newfdp->fd_builtin_files;
1350 newfdp->fd_nfiles = NDFILE;
1351 newfdp->fd_knlistsize = -1;
1352 newfdp->fd_lastfile = -1;
1353 spin_init(&newfdp->fd_spin);
1359 * Share a filedesc structure.
1362 fdshare(struct proc *p)
1364 p->p_fd->fd_refcnt++;
1369 * Copy a filedesc structure.
1372 fdcopy(struct proc *p)
1374 struct filedesc *newfdp, *fdp = p->p_fd;
1375 struct fdnode *fdnode;
1378 /* Certain daemons might not have file descriptors. */
1382 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK);
1384 if (newfdp->fd_cdir) {
1385 vref(newfdp->fd_cdir);
1386 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1389 * We must check for fd_rdir here, at least for now because
1390 * the init process is created before we have access to the
1391 * rootvode to take a reference to it.
1393 if (newfdp->fd_rdir) {
1394 vref(newfdp->fd_rdir);
1395 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1397 if (newfdp->fd_jdir) {
1398 vref(newfdp->fd_jdir);
1399 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1401 newfdp->fd_refcnt = 1;
1402 spin_init(&newfdp->fd_spin);
1405 * If the number of open files fits in the internal arrays
1406 * of the open file structure, use them, otherwise allocate
1407 * additional memory for the number of descriptors currently
1410 if (newfdp->fd_lastfile < NDFILE) {
1411 newfdp->fd_files = newfdp->fd_builtin_files;
1415 * Compute the smallest file table size
1416 * for the file descriptors currently in use,
1417 * allowing the table to shrink.
1419 i = newfdp->fd_nfiles;
1420 while ((i-1)/2 > newfdp->fd_lastfile && (i-1)/2 > NDFILE)
1422 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1423 M_FILEDESC, M_WAITOK);
1425 newfdp->fd_nfiles = i;
1427 if (fdp->fd_files != fdp->fd_builtin_files ||
1428 newfdp->fd_files != newfdp->fd_builtin_files
1430 bcopy(fdp->fd_files, newfdp->fd_files,
1431 i * sizeof(struct fdnode));
1435 * kq descriptors cannot be copied. Since we haven't ref'd the
1436 * copied files yet we can ignore the return value from funsetfd().
1438 if (newfdp->fd_knlistsize != -1) {
1439 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1440 fdnode = &newfdp->fd_files[i];
1441 if (fdnode->fp && fdnode->fp->f_type == DTYPE_KQUEUE) {
1442 (void)funsetfd(newfdp, i);
1445 newfdp->fd_knlist = NULL;
1446 newfdp->fd_knlistsize = -1;
1447 newfdp->fd_knhash = NULL;
1448 newfdp->fd_knhashmask = 0;
1452 * Ref the copied file pointers. Make sure any reserved but
1453 * unassigned descriptors are cleared in the copy.
1455 for (i = 0; i <= newfdp->fd_lastfile; ++i) {
1456 fdnode = &newfdp->fd_files[i];
1457 if (fdnode->reserved) {
1458 fdreserve(newfdp, i, -1);
1459 fdnode->reserved = 0;
1469 * Release a filedesc structure.
1472 fdfree(struct proc *p)
1474 struct thread *td = p->p_thread;
1475 struct filedesc *fdp = p->p_fd;
1476 struct fdnode *fdnode;
1478 struct filedesc_to_leader *fdtol;
1483 /* Certain daemons might not have file descriptors. */
1487 /* Check for special need to clear POSIX style locks */
1489 if (fdtol != NULL) {
1490 KASSERT(fdtol->fdl_refcount > 0,
1491 ("filedesc_to_refcount botch: fdl_refcount=%d",
1492 fdtol->fdl_refcount));
1493 if (fdtol->fdl_refcount == 1 &&
1494 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1495 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1496 fdnode = &fdp->fd_files[i];
1497 if (fdnode->fp == NULL ||
1498 fdnode->fp->f_type != DTYPE_VNODE) {
1503 lf.l_whence = SEEK_SET;
1506 lf.l_type = F_UNLCK;
1507 vp = (struct vnode *)fp->f_data;
1508 (void) VOP_ADVLOCK(vp,
1509 (caddr_t)p->p_leader,
1517 if (fdtol->fdl_refcount == 1) {
1518 if (fdp->fd_holdleaderscount > 0 &&
1519 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1521 * close() or do_dup() has cleared a reference
1522 * in a shared file descriptor table.
1524 fdp->fd_holdleaderswakeup = 1;
1525 tsleep(&fdp->fd_holdleaderscount,
1529 if (fdtol->fdl_holdcount > 0) {
1531 * Ensure that fdtol->fdl_leader
1532 * remains valid in closef().
1534 fdtol->fdl_wakeup = 1;
1535 tsleep(fdtol, 0, "fdlhold", 0);
1539 fdtol->fdl_refcount--;
1540 if (fdtol->fdl_refcount == 0 &&
1541 fdtol->fdl_holdcount == 0) {
1542 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1543 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1548 free(fdtol, M_FILEDESC_TO_LEADER);
1550 if (--fdp->fd_refcnt > 0)
1553 * we are the last reference to the structure, we can
1554 * safely assume it will not change out from under us.
1556 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1557 if (fdp->fd_files[i].fp)
1558 closef(fdp->fd_files[i].fp, td);
1560 if (fdp->fd_files != fdp->fd_builtin_files)
1561 free(fdp->fd_files, M_FILEDESC);
1563 cache_drop(fdp->fd_ncdir);
1564 vrele(fdp->fd_cdir);
1567 cache_drop(fdp->fd_nrdir);
1568 vrele(fdp->fd_rdir);
1571 cache_drop(fdp->fd_njdir);
1572 vrele(fdp->fd_jdir);
1575 free(fdp->fd_knlist, M_KQUEUE);
1577 free(fdp->fd_knhash, M_KQUEUE);
1578 free(fdp, M_FILEDESC);
1582 * Retrieve and reference the file pointer associated with a descriptor.
1587 holdfp(struct filedesc *fdp, int fd, int flag)
1591 spin_lock_rd(&fdp->fd_spin);
1592 if (((u_int)fd) >= fdp->fd_nfiles) {
1596 if ((fp = fdp->fd_files[fd].fp) == NULL)
1598 if ((fp->f_flag & flag) == 0 && flag != -1) {
1604 spin_unlock_rd(&fdp->fd_spin);
1609 * holdsock() - load the struct file pointer associated
1610 * with a socket into *fpp. If an error occurs, non-zero
1611 * will be returned and *fpp will be set to NULL.
1614 holdsock(struct filedesc *fdp, int fdes, struct file **fpp)
1620 if ((unsigned)fdes >= fdp->fd_nfiles)
1622 if ((fp = fdp->fd_files[fdes].fp) == NULL)
1624 if (fp->f_type != DTYPE_SOCKET)
1632 * Convert a user file descriptor to a kernel file entry.
1635 getvnode(struct filedesc *fdp, int fd, struct file **fpp)
1639 if ((u_int)fd >= fdp->fd_nfiles ||
1640 (fp = fdp->fd_files[fd].fp) == NULL)
1642 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO)
1649 * For setugid programs, we don't want to people to use that setugidness
1650 * to generate error messages which write to a file which otherwise would
1651 * otherwise be off-limits to the process.
1653 * This is a gross hack to plug the hole. A better solution would involve
1654 * a special vop or other form of generalized access control mechanism. We
1655 * go ahead and just reject all procfs file systems accesses as dangerous.
1657 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1658 * sufficient. We also don't for check setugidness since we know we are.
1661 is_unsafe(struct file *fp)
1663 if (fp->f_type == DTYPE_VNODE &&
1664 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1670 * Make this setguid thing safe, if at all possible.
1673 setugidsafety(struct proc *p)
1675 struct thread *td = p->p_thread;
1676 struct filedesc *fdp = p->p_fd;
1679 /* Certain daemons might not have file descriptors. */
1684 * note: fdp->fd_files may be reallocated out from under us while
1685 * we are blocked in a close. Be careful!
1687 for (i = 0; i <= fdp->fd_lastfile; i++) {
1690 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1693 if (i < fdp->fd_knlistsize)
1694 knote_fdclose(p, i);
1696 * NULL-out descriptor prior to close to avoid
1697 * a race while close blocks.
1699 if ((fp = funsetfd(fdp, i)) != NULL)
1706 * Close any files on exec?
1709 fdcloseexec(struct proc *p)
1711 struct thread *td = p->p_thread;
1712 struct filedesc *fdp = p->p_fd;
1715 /* Certain daemons might not have file descriptors. */
1720 * We cannot cache fd_files since operations may block and rip
1721 * them out from under us.
1723 for (i = 0; i <= fdp->fd_lastfile; i++) {
1724 if (fdp->fd_files[i].fp != NULL &&
1725 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1728 if (i < fdp->fd_knlistsize)
1729 knote_fdclose(p, i);
1731 * NULL-out descriptor prior to close to avoid
1732 * a race while close blocks.
1734 if ((fp = funsetfd(fdp, i)) != NULL)
1741 * It is unsafe for set[ug]id processes to be started with file
1742 * descriptors 0..2 closed, as these descriptors are given implicit
1743 * significance in the Standard C library. fdcheckstd() will create a
1744 * descriptor referencing /dev/null for each of stdin, stdout, and
1745 * stderr that is not already open.
1748 fdcheckstd(struct proc *p)
1750 struct nlookupdata nd;
1751 struct filedesc *fdp;
1754 int i, error, flags, devnull;
1761 for (i = 0; i < 3; i++) {
1762 if (fdp->fd_files[i].fp != NULL)
1765 if ((error = falloc(p, &fp, &devnull)) != 0)
1768 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1769 NLC_FOLLOW|NLC_LOCKVP);
1770 flags = FREAD | FWRITE;
1772 error = vn_open(&nd, fp, flags, 0);
1774 fsetfd(p, fp, devnull);
1776 fsetfd(p, NULL, devnull);
1781 KKASSERT(i == devnull);
1783 error = kern_dup(DUP_FIXED, devnull, i, &retval);
1792 * Internal form of close.
1793 * Decrement reference count on file structure.
1794 * Note: td and/or p may be NULL when closing a file
1795 * that was being passed in a message.
1798 closef(struct file *fp, struct thread *td)
1802 struct filedesc_to_leader *fdtol;
1809 p = NULL; /* allow no proc association */
1811 p = td->td_proc; /* can also be NULL */
1814 * POSIX record locking dictates that any close releases ALL
1815 * locks owned by this process. This is handled by setting
1816 * a flag in the unlock to free ONLY locks obeying POSIX
1817 * semantics, and not to free BSD-style file locks.
1818 * If the descriptor was in a message, POSIX-style locks
1819 * aren't passed with the descriptor.
1822 fp->f_type == DTYPE_VNODE) {
1823 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1824 lf.l_whence = SEEK_SET;
1827 lf.l_type = F_UNLCK;
1828 vp = (struct vnode *)fp->f_data;
1829 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1833 if (fdtol != NULL) {
1835 * Handle special case where file descriptor table
1836 * is shared between multiple process leaders.
1838 for (fdtol = fdtol->fdl_next;
1839 fdtol != p->p_fdtol;
1840 fdtol = fdtol->fdl_next) {
1841 if ((fdtol->fdl_leader->p_flag &
1844 fdtol->fdl_holdcount++;
1845 lf.l_whence = SEEK_SET;
1848 lf.l_type = F_UNLCK;
1849 vp = (struct vnode *)fp->f_data;
1850 (void) VOP_ADVLOCK(vp,
1851 (caddr_t)fdtol->fdl_leader,
1852 F_UNLCK, &lf, F_POSIX);
1853 fdtol->fdl_holdcount--;
1854 if (fdtol->fdl_holdcount == 0 &&
1855 fdtol->fdl_wakeup != 0) {
1856 fdtol->fdl_wakeup = 0;
1868 * fhold() can only be called if f_count is already at least 1 (i.e. the
1869 * caller of fhold() already has a reference to the file pointer in some
1870 * manner or other). In addition, fhold() must be callable with a spinlock
1871 * held on the governing structure that the caller went through to find the
1875 fhold(struct file *fp)
1877 atomic_add_int(&fp->f_count, 1);
1881 * MPSAFE TODO: VOP_ADVLOCK, fo_close
1883 * A spinlock is required to handle 1->0 transitions on f_count.
1886 fdrop(struct file *fp)
1892 spin_lock_wr(&fp->f_spin);
1893 if (--fp->f_count > 0) {
1894 spin_unlock_wr(&fp->f_spin);
1897 spin_unlock_wr(&fp->f_spin);
1900 * The last reference has gone away, we own the fp structure free
1903 if (fp->f_count < 0)
1904 panic("fdrop: count < 0");
1905 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1906 lf.l_whence = SEEK_SET;
1909 lf.l_type = F_UNLCK;
1910 vp = (struct vnode *)fp->f_data;
1911 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
1913 if (fp->f_ops != &badfileops)
1914 error = fo_close(fp);
1922 * Apply an advisory lock on a file descriptor.
1924 * Just attempt to get a record lock of the requested type on
1925 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1929 flock(struct flock_args *uap)
1931 struct proc *p = curproc;
1932 struct filedesc *fdp = p->p_fd;
1937 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1938 (fp = fdp->fd_files[uap->fd].fp) == NULL)
1940 if (fp->f_type != DTYPE_VNODE)
1941 return (EOPNOTSUPP);
1942 vp = (struct vnode *)fp->f_data;
1943 lf.l_whence = SEEK_SET;
1946 if (uap->how & LOCK_UN) {
1947 lf.l_type = F_UNLCK;
1948 fp->f_flag &= ~FHASLOCK;
1949 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0));
1951 if (uap->how & LOCK_EX)
1952 lf.l_type = F_WRLCK;
1953 else if (uap->how & LOCK_SH)
1954 lf.l_type = F_RDLCK;
1957 fp->f_flag |= FHASLOCK;
1958 if (uap->how & LOCK_NB)
1959 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0));
1960 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT));
1964 * File Descriptor pseudo-device driver (/dev/fd/).
1966 * Opening minor device N dup()s the file (if any) connected to file
1967 * descriptor N belonging to the calling process. Note that this driver
1968 * consists of only the ``open()'' routine, because all subsequent
1969 * references to this file will be direct to the other driver.
1973 fdopen(dev_t dev, int mode, int type, struct thread *td)
1975 KKASSERT(td->td_lwp != NULL);
1978 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
1979 * the file descriptor being sought for duplication. The error
1980 * return ensures that the vnode for this device will be released
1981 * by vn_open. Open will detect this special error and take the
1982 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1983 * will simply report the error.
1985 td->td_lwp->lwp_dupfd = minor(dev);
1990 * The caller has reserved the file descriptor dfd for us. On success we
1991 * must fsetfd() it. On failure the caller will clean it up.
1994 dupfdopen(struct proc *p, int dfd, int sfd, int mode, int error)
1996 struct filedesc *fdp = p->p_fd;
2000 if ((wfp = holdfp(fdp, sfd, -1)) == NULL)
2004 * There are two cases of interest here.
2006 * For ENODEV simply dup sfd to file descriptor dfd and return.
2008 * For ENXIO steal away the file structure from sfd and store it
2009 * dfd. sfd is effectively closed by this operation.
2011 * Any other error code is just returned.
2016 * Check that the mode the file is being opened for is a
2017 * subset of the mode of the existing descriptor.
2019 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
2021 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2022 fsetfd(p, wfp, dfd);
2027 * Steal away the file pointer from dfd, and stuff it into indx.
2029 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2030 fsetfd(p, wfp, dfd);
2031 if ((xfp = funsetfd(fdp, sfd)) != NULL)
2033 KKASSERT(xfp == wfp); /* XXX MP RACE */
2044 struct filedesc_to_leader *
2045 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2046 struct proc *leader)
2048 struct filedesc_to_leader *fdtol;
2050 fdtol = malloc(sizeof(struct filedesc_to_leader),
2051 M_FILEDESC_TO_LEADER, M_WAITOK);
2052 fdtol->fdl_refcount = 1;
2053 fdtol->fdl_holdcount = 0;
2054 fdtol->fdl_wakeup = 0;
2055 fdtol->fdl_leader = leader;
2057 fdtol->fdl_next = old->fdl_next;
2058 fdtol->fdl_prev = old;
2059 old->fdl_next = fdtol;
2060 fdtol->fdl_next->fdl_prev = fdtol;
2062 fdtol->fdl_next = fdtol;
2063 fdtol->fdl_prev = fdtol;
2069 * Get file structures.
2072 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2074 struct kinfo_file kf;
2075 struct filedesc *fdp;
2084 * Note: because the number of file descriptors is calculated
2085 * in different ways for sizing vs returning the data,
2086 * there is information leakage from the first loop. However,
2087 * it is of a similar order of magnitude to the leakage from
2088 * global system statistics such as kern.openfiles.
2090 * When just doing a count, note that we cannot just count
2091 * the elements and add f_count via the filehead list because
2092 * threaded processes share their descriptor table and f_count might
2093 * still be '1' in that case.
2095 * Since the SYSCTL op can block, we must hold the process to
2096 * prevent it being ripped out from under us either in the
2097 * file descriptor loop or in the greater LIST_FOREACH. The
2098 * process may be in varying states of disrepair. If the process
2099 * is in SZOMB we may have caught it just as it is being removed
2100 * from the allproc list, we must skip it in that case to maintain
2101 * an unbroken chain through the allproc list.
2105 LIST_FOREACH(p, &allproc, p_list) {
2106 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
2108 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
2110 if ((fdp = p->p_fd) == NULL)
2113 for (n = 0; n < fdp->fd_nfiles; ++n) {
2114 if ((fp = fdp->fd_files[n].fp) == NULL)
2116 if (req->oldptr == NULL) {
2119 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2120 kcore_make_file(&kf, fp, p->p_pid, uid, n);
2121 error = SYSCTL_OUT(req, &kf, sizeof(kf));
2132 * When just calculating the size, overestimate a bit to try to
2133 * prevent system activity from causing the buffer-fill call
2136 if (req->oldptr == NULL) {
2137 count = (count + 16) + (count / 10);
2138 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
2143 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2144 0, 0, sysctl_kern_file, "S,file", "Entire file table");
2146 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2147 &maxfilesperproc, 0, "Maximum files allowed open per process");
2149 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2150 &maxfiles, 0, "Maximum number of files");
2152 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
2153 &maxfilesrootres, 0, "Descriptors reserved for root use");
2155 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2156 &nfiles, 0, "System-wide number of open files");
2159 fildesc_drvinit(void *unused)
2163 cdevsw_add(&fildesc_cdevsw, 0, 0);
2164 for (fd = 0; fd < NUMFDESC; fd++) {
2165 make_dev(&fildesc_cdevsw, fd,
2166 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2168 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2169 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2170 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2173 struct fileops badfileops = {
2197 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2203 badfo_poll(struct file *fp, int events, struct ucred *cred)
2209 badfo_kqfilter(struct file *fp, struct knote *kn)
2215 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2221 badfo_close(struct file *fp)
2227 badfo_shutdown(struct file *fp, int how)
2233 nofo_shutdown(struct file *fp, int how)
2235 return (EOPNOTSUPP);
2238 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2239 fildesc_drvinit,NULL)