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.59 2006/05/22 00:52:29 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 void 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 * System calls on descriptors.
161 getdtablesize(struct getdtablesize_args *uap)
163 struct proc *p = curproc;
166 min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
171 * Duplicate a file descriptor to a particular value.
173 * note: keep in mind that a potential race condition exists when closing
174 * descriptors from a shared descriptor table (via rfork).
178 dup2(struct dup2_args *uap)
182 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
188 * Duplicate a file descriptor.
192 dup(struct dup_args *uap)
196 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
202 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
204 struct thread *td = curthread;
205 struct proc *p = td->td_proc;
209 int tmp, error, flg = F_POSIX;
213 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
219 if (newmin >= p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
220 newmin > maxfilesperproc) {
224 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
228 error = fgetfdflags(p->p_fd, fd, &tmp);
230 dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
234 if (dat->fc_cloexec & FD_CLOEXEC)
235 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
237 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
241 dat->fc_flags = OFLAGS(fp->f_flag);
246 fp->f_flag &= ~FCNTLFLAGS;
247 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
248 tmp = fp->f_flag & FNONBLOCK;
249 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
252 tmp = fp->f_flag & FASYNC;
253 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
256 fp->f_flag &= ~FNONBLOCK;
258 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
262 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
266 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
271 /* Fall into F_SETLK */
274 if (fp->f_type != DTYPE_VNODE) {
278 vp = (struct vnode *)fp->f_data;
281 * copyin/lockop may block
283 if (dat->fc_flock.l_whence == SEEK_CUR)
284 dat->fc_flock.l_start += fp->f_offset;
286 switch (dat->fc_flock.l_type) {
288 if ((fp->f_flag & FREAD) == 0) {
292 p->p_leader->p_flag |= P_ADVLOCK;
293 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
294 &dat->fc_flock, flg);
297 if ((fp->f_flag & FWRITE) == 0) {
301 p->p_leader->p_flag |= P_ADVLOCK;
302 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
303 &dat->fc_flock, flg);
306 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
307 &dat->fc_flock, F_POSIX);
315 * It is possible to race a close() on the descriptor while
316 * we were blocked getting the lock. If this occurs the
317 * close might not have caught the lock.
319 if (checkfpclosed(p->p_fd, fd, fp)) {
320 dat->fc_flock.l_whence = SEEK_SET;
321 dat->fc_flock.l_start = 0;
322 dat->fc_flock.l_len = 0;
323 dat->fc_flock.l_type = F_UNLCK;
324 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
325 F_UNLCK, &dat->fc_flock, F_POSIX);
330 if (fp->f_type != DTYPE_VNODE) {
334 vp = (struct vnode *)fp->f_data;
336 * copyin/lockop may block
338 if (dat->fc_flock.l_type != F_RDLCK &&
339 dat->fc_flock.l_type != F_WRLCK &&
340 dat->fc_flock.l_type != F_UNLCK) {
344 if (dat->fc_flock.l_whence == SEEK_CUR)
345 dat->fc_flock.l_start += fp->f_offset;
346 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
347 &dat->fc_flock, F_POSIX);
358 * The file control system call.
361 fcntl(struct fcntl_args *uap)
368 dat.fc_fd = uap->arg;
371 dat.fc_cloexec = uap->arg;
374 dat.fc_flags = uap->arg;
377 dat.fc_owner = uap->arg;
382 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
383 sizeof(struct flock));
389 error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
394 uap->sysmsg_result = dat.fc_fd;
397 uap->sysmsg_result = dat.fc_cloexec;
400 uap->sysmsg_result = dat.fc_flags;
403 uap->sysmsg_result = dat.fc_owner;
405 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
406 sizeof(struct flock));
415 * Common code for dup, dup2, and fcntl(F_DUPFD).
417 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
418 * kern_dup() to destructively dup over an existing file descriptor if new
419 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
420 * unused file descriptor that is greater than or equal to new.
423 kern_dup(enum dup_type type, int old, int new, int *res)
425 struct thread *td = curthread;
426 struct proc *p = td->td_proc;
427 struct filedesc *fdp = p->p_fd;
431 boolean_t fdalloced = FALSE;
435 * Verify that we have a valid descriptor to dup from and
436 * possibly to dup to.
438 if (old < 0 || new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
439 new >= maxfilesperproc)
441 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL)
443 if (type == DUP_FIXED && old == new) {
447 fp = fdp->fd_files[old].fp;
451 * Expand the table for the new descriptor if needed. This may
452 * block and drop and reacquire the fidedesc lock.
454 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
455 error = fdalloc(p, new, &newfd);
462 if (type == DUP_VARIABLE)
466 * If the old file changed out from under us then treat it as a
467 * bad file descriptor. Userland should do its own locking to
470 if (fdp->fd_files[old].fp != fp) {
471 if (fdp->fd_files[new].fp == NULL) {
473 fdreserve(fdp, newfd, -1);
474 if (new < fdp->fd_freefile)
475 fdp->fd_freefile = new;
476 while (fdp->fd_lastfile > 0 &&
477 fdp->fd_files[fdp->fd_lastfile].fp == NULL)
483 KASSERT(old != new, ("new fd is same as old"));
486 * Save info on the descriptor being overwritten. We have
487 * to do the unmap now, but we cannot close it without
488 * introducing an ownership race for the slot.
490 delfp = fdp->fd_files[new].fp;
491 if (delfp != NULL && p->p_fdtol != NULL) {
493 * Ask fdfree() to sleep to ensure that all relevant
494 * process leaders can be traversed in closef().
496 fdp->fd_holdleaderscount++;
500 KASSERT(delfp == NULL || type == DUP_FIXED,
501 ("dup() picked an open file"));
504 * Duplicate the source descriptor, update lastfile
506 if (new > fdp->fd_lastfile)
507 fdp->fd_lastfile = new;
508 if (!fdalloced && fdp->fd_files[new].fp == NULL)
509 fdreserve(fdp, new, 1);
510 fdp->fd_files[new].fp = fp;
511 fdp->fd_files[new].fileflags =
512 fdp->fd_files[old].fileflags & ~UF_EXCLOSE;
516 * If we dup'd over a valid file, we now own the reference to it
517 * and must dispose of it using closef() semantics (as if a
518 * close() were performed on it).
521 (void) closef(delfp, td);
523 fdp->fd_holdleaderscount--;
524 if (fdp->fd_holdleaderscount == 0 &&
525 fdp->fd_holdleaderswakeup != 0) {
526 fdp->fd_holdleaderswakeup = 0;
527 wakeup(&fdp->fd_holdleaderscount);
535 * If sigio is on the list associated with a process or process group,
536 * disable signalling from the device, remove sigio from the list and
540 funsetown(struct sigio *sigio)
545 *(sigio->sio_myref) = NULL;
547 if (sigio->sio_pgid < 0) {
548 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
550 } else /* if ((*sigiop)->sio_pgid > 0) */ {
551 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
554 crfree(sigio->sio_ucred);
555 free(sigio, M_SIGIO);
558 /* Free a list of sigio structures. */
560 funsetownlst(struct sigiolst *sigiolst)
564 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
569 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
571 * After permission checking, add a sigio structure to the sigio list for
572 * the process or process group.
575 fsetown(pid_t pgid, struct sigio **sigiop)
591 * Policy - Don't allow a process to FSETOWN a process
592 * in another session.
594 * Remove this test to allow maximum flexibility or
595 * restrict FSETOWN to the current process or process
596 * group for maximum safety.
598 if (proc->p_session != curproc->p_session)
602 } else /* if (pgid < 0) */ {
603 pgrp = pgfind(-pgid);
608 * Policy - Don't allow a process to FSETOWN a process
609 * in another session.
611 * Remove this test to allow maximum flexibility or
612 * restrict FSETOWN to the current process or process
613 * group for maximum safety.
615 if (pgrp->pg_session != curproc->p_session)
621 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
623 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
624 sigio->sio_proc = proc;
626 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
627 sigio->sio_pgrp = pgrp;
629 sigio->sio_pgid = pgid;
630 sigio->sio_ucred = crhold(curproc->p_ucred);
631 /* It would be convenient if p_ruid was in ucred. */
632 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
633 sigio->sio_myref = sigiop;
641 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
644 fgetown(struct sigio *sigio)
646 return (sigio != NULL ? sigio->sio_pgid : 0);
650 * Close many file descriptors.
655 closefrom(struct closefrom_args *uap)
657 return(kern_closefrom(uap->fd));
661 kern_closefrom(int fd)
663 struct thread *td = curthread;
664 struct proc *p = td->td_proc;
665 struct filedesc *fdp;
670 if (fd < 0 || fd > fdp->fd_lastfile)
674 if (kern_close(fdp->fd_lastfile) == EINTR)
676 } while (fdp->fd_lastfile > fd);
682 * Close a file descriptor.
687 close(struct close_args *uap)
689 return(kern_close(uap->fd));
695 struct thread *td = curthread;
696 struct proc *p = td->td_proc;
697 struct filedesc *fdp;
705 if ((unsigned)fd >= fdp->fd_nfiles ||
706 (fp = fdp->fd_files[fd].fp) == NULL)
710 if (p->p_fdtol != NULL) {
712 * Ask fdfree() to sleep to ensure that all relevant
713 * process leaders can be traversed in closef().
715 fdp->fd_holdleaderscount++;
720 * we now hold the fp reference that used to be owned by the descriptor
723 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
725 if (fd < fdp->fd_knlistsize)
726 knote_fdclose(p, fd);
727 error = closef(fp, td);
729 fdp->fd_holdleaderscount--;
730 if (fdp->fd_holdleaderscount == 0 &&
731 fdp->fd_holdleaderswakeup != 0) {
732 fdp->fd_holdleaderswakeup = 0;
733 wakeup(&fdp->fd_holdleaderscount);
740 * shutdown_args(int fd, int how)
743 kern_shutdown(int fd, int how)
745 struct thread *td = curthread;
746 struct proc *p = td->td_proc;
747 struct filedesc *fdp;
754 if ((unsigned)fd >= fdp->fd_nfiles ||
755 (fp = fdp->fd_files[fd].fp) == NULL)
758 error = fo_shutdown(fp, how);
765 shutdown(struct shutdown_args *uap)
769 error = kern_shutdown(uap->s, uap->how);
775 kern_fstat(int fd, struct stat *ub)
777 struct thread *td = curthread;
778 struct proc *p = td->td_proc;
779 struct filedesc *fdp;
786 if ((unsigned)fd >= fdp->fd_nfiles ||
787 (fp = fdp->fd_files[fd].fp) == NULL)
790 error = fo_stat(fp, ub, p->p_ucred);
797 * Return status information about a file descriptor.
800 fstat(struct fstat_args *uap)
805 error = kern_fstat(uap->fd, &st);
808 error = copyout(&st, uap->sb, sizeof(st));
813 * Return pathconf information about a file descriptor.
817 fpathconf(struct fpathconf_args *uap)
819 struct thread *td = curthread;
820 struct proc *p = td->td_proc;
821 struct filedesc *fdp;
828 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
829 (fp = fdp->fd_files[uap->fd].fp) == NULL)
834 switch (fp->f_type) {
837 if (uap->name != _PC_PIPE_BUF) {
840 uap->sysmsg_result = PIPE_BUF;
846 vp = (struct vnode *)fp->f_data;
847 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
858 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
861 fdgrow(struct filedesc *fdp, int want)
863 struct fdnode *newfiles;
864 struct fdnode *oldfiles;
869 /* nf has to be of the form 2^n - 1 */
871 } while (nf <= want);
873 newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
876 * deal with file-table extend race that might have occured
877 * when malloc was blocked.
879 if (fdp->fd_nfiles >= nf) {
880 free(newfiles, M_FILEDESC);
884 * Copy the existing ofile and ofileflags arrays
885 * and zero the new portion of each array.
887 extra = nf - fdp->fd_nfiles;
888 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
889 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
891 oldfiles = fdp->fd_files;
892 fdp->fd_files = newfiles;
895 if (oldfiles != fdp->fd_builtin_files)
896 free(oldfiles, M_FILEDESC);
901 * Number of nodes in right subtree, including the root.
904 right_subtree_size(int n)
906 return (n ^ (n | (n + 1)));
913 right_ancestor(int n)
915 return (n | (n + 1));
924 return ((n & (n + 1)) - 1);
929 fdreserve(struct filedesc *fdp, int fd, int incr)
932 fdp->fd_files[fd].allocated += incr;
933 KKASSERT(fdp->fd_files[fd].allocated >= 0);
934 fd = left_ancestor(fd);
939 * Allocate a file descriptor for the process.
942 fdalloc(struct proc *p, int want, int *result)
944 struct filedesc *fdp = p->p_fd;
945 int fd, rsize, rsum, node, lim;
947 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
950 if (want >= fdp->fd_nfiles)
954 * Search for a free descriptor starting at the higher
955 * of want or fd_freefile. If that fails, consider
956 * expanding the ofile array.
959 /* move up the tree looking for a subtree with a free node */
960 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
961 fd = right_ancestor(fd)) {
962 if (fdp->fd_files[fd].allocated == 0)
965 rsize = right_subtree_size(fd);
966 if (fdp->fd_files[fd].allocated == rsize)
967 continue; /* right subtree full */
970 * Free fd is in the right subtree of the tree rooted at fd.
971 * Call that subtree R. Look for the smallest (leftmost)
972 * subtree of R with an unallocated fd: continue moving
973 * down the left branch until encountering a full left
974 * subtree, then move to the right.
976 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
978 rsum += fdp->fd_files[node].allocated;
979 if (fdp->fd_files[fd].allocated == rsum + rsize) {
980 fd = node; /* move to the right */
981 if (fdp->fd_files[node].allocated == 0)
990 * No space in current array. Expand?
992 if (fdp->fd_nfiles >= lim)
998 KKASSERT(fd < fdp->fd_nfiles);
999 fdp->fd_files[fd].fileflags = 0;
1000 if (fd > fdp->fd_lastfile)
1001 fdp->fd_lastfile = fd;
1002 if (want <= fdp->fd_freefile)
1003 fdp->fd_freefile = fd;
1005 KKASSERT(fdp->fd_files[fd].fp == NULL);
1006 fdreserve(fdp, fd, 1);
1011 * Check to see whether n user file descriptors
1012 * are available to the process p.
1015 fdavail(struct proc *p, int n)
1017 struct filedesc *fdp = p->p_fd;
1018 struct fdnode *fdnode;
1021 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1022 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0)
1025 last = min(fdp->fd_nfiles, lim);
1026 fdnode = &fdp->fd_files[fdp->fd_freefile];
1027 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1028 if (fdnode->fp == NULL && --n <= 0)
1036 * Create a new open file structure and allocate a file decriptor
1037 * for the process that refers to it. If p is NULL, no descriptor
1038 * is allocated and the file pointer is returned unassociated with
1039 * any process. resultfd is only used if p is not NULL and may
1040 * separately be NULL indicating that you don't need the returned fd.
1042 * A held file pointer is returned. If a descriptor has been allocated
1043 * an additional hold on the fp will be made due to the fd_files[]
1047 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1049 static struct timeval lastfail;
1057 * Handle filetable full issues and root overfill.
1059 if (nfiles >= maxfiles - maxfilesrootres &&
1060 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1061 if (ppsratecheck(&lastfail, &curfail, 1)) {
1062 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1063 (p ? p->p_ucred->cr_ruid : -1));
1070 * Allocate a new file descriptor.
1073 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1074 spin_init(&fp->f_spin);
1076 fp->f_ops = &badfileops;
1079 fp->f_cred = crhold(p->p_ucred);
1081 fp->f_cred = crhold(proc0.p_ucred);
1082 LIST_INSERT_HEAD(&filehead, fp, f_list);
1084 if ((error = fsetfd(p, fp, resultfd)) != 0) {
1097 * fdealloc - deallocate a descriptor allocated with falloc. The deallocation
1098 * only occurs if the passed file pointer matches the descriptor.
1101 fdealloc(struct proc *p, struct file *fp, int fd)
1103 struct filedesc *fdp = p->p_fd;
1105 if (((u_int)fd) >= fdp->fd_nfiles || fdp->fd_files[fd].fp != fp)
1107 fdp->fd_files[fd].fp = NULL;
1108 fdp->fd_files[fd].fileflags = 0;
1109 fdreserve(fdp, fd, -1);
1110 if (fd < fdp->fd_freefile)
1111 fdp->fd_freefile = fd;
1121 checkfpclosed(struct filedesc *fdp, int fd, struct file *fp)
1125 spin_lock_rd(&fdp->fd_spin);
1126 if ((unsigned) fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1130 spin_unlock_rd(&fdp->fd_spin);
1135 * Associate a file pointer with a file descriptor. On success the fp
1136 * will have an additional ref representing the fd_files[] association.
1139 fsetfd(struct proc *p, struct file *fp, int *resultfd)
1144 if ((error = fdalloc(p, 0, &fd)) == 0) {
1146 p->p_fd->fd_files[fd].fp = fp;
1154 funsetfd(struct filedesc *fdp, int fd)
1156 fdp->fd_files[fd].fp = NULL;
1157 fdp->fd_files[fd].fileflags = 0;
1158 fdreserve(fdp, fd, -1);
1159 if (fd < fdp->fd_freefile)
1160 fdp->fd_freefile = fd;
1167 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1171 spin_lock_rd(&fdp->fd_spin);
1172 if (((u_int)fd) >= fdp->fd_nfiles) {
1174 } else if (fdp->fd_files[fd].fp == NULL) {
1177 *flagsp = fdp->fd_files[fd].fileflags;
1180 spin_unlock_rd(&fdp->fd_spin);
1188 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1192 spin_lock_wr(&fdp->fd_spin);
1193 if (((u_int)fd) >= fdp->fd_nfiles) {
1195 } else if (fdp->fd_files[fd].fp == NULL) {
1198 fdp->fd_files[fd].fileflags |= add_flags;
1201 spin_unlock_wr(&fdp->fd_spin);
1209 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1213 spin_lock_wr(&fdp->fd_spin);
1214 if (((u_int)fd) >= fdp->fd_nfiles) {
1216 } else if (fdp->fd_files[fd].fp == NULL) {
1219 fdp->fd_files[fd].fileflags &= ~rem_flags;
1222 spin_unlock_wr(&fdp->fd_spin);
1227 fsetcred(struct file *fp, struct ucred *cr)
1235 * Free a file descriptor.
1238 ffree(struct file *fp)
1240 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1241 LIST_REMOVE(fp, f_list);
1244 cache_drop(fp->f_ncp);
1252 * called from init_main, initialize filedesc0 for proc0.
1255 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1259 fdp0->fd_refcnt = 1;
1260 fdp0->fd_cmask = cmask;
1261 fdp0->fd_files = fdp0->fd_builtin_files;
1262 fdp0->fd_nfiles = NDFILE;
1263 spin_init(&fdp0->fd_spin);
1267 * Build a new filedesc structure.
1270 fdinit(struct proc *p)
1272 struct filedesc *newfdp;
1273 struct filedesc *fdp = p->p_fd;
1275 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1277 newfdp->fd_cdir = fdp->fd_cdir;
1278 vref(newfdp->fd_cdir);
1279 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1283 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1284 * proc0, but should unconditionally exist in other processes.
1287 newfdp->fd_rdir = fdp->fd_rdir;
1288 vref(newfdp->fd_rdir);
1289 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1292 newfdp->fd_jdir = fdp->fd_jdir;
1293 vref(newfdp->fd_jdir);
1294 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1297 /* Create the file descriptor table. */
1298 newfdp->fd_refcnt = 1;
1299 newfdp->fd_cmask = cmask;
1300 newfdp->fd_files = newfdp->fd_builtin_files;
1301 newfdp->fd_nfiles = NDFILE;
1302 newfdp->fd_knlistsize = -1;
1303 spin_init(&newfdp->fd_spin);
1309 * Share a filedesc structure.
1312 fdshare(struct proc *p)
1314 p->p_fd->fd_refcnt++;
1319 * Copy a filedesc structure.
1322 fdcopy(struct proc *p)
1324 struct filedesc *newfdp, *fdp = p->p_fd;
1325 struct fdnode *fdnode;
1328 /* Certain daemons might not have file descriptors. */
1332 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK);
1334 if (newfdp->fd_cdir) {
1335 vref(newfdp->fd_cdir);
1336 newfdp->fd_ncdir = cache_hold(newfdp->fd_ncdir);
1339 * We must check for fd_rdir here, at least for now because
1340 * the init process is created before we have access to the
1341 * rootvode to take a reference to it.
1343 if (newfdp->fd_rdir) {
1344 vref(newfdp->fd_rdir);
1345 newfdp->fd_nrdir = cache_hold(newfdp->fd_nrdir);
1347 if (newfdp->fd_jdir) {
1348 vref(newfdp->fd_jdir);
1349 newfdp->fd_njdir = cache_hold(newfdp->fd_njdir);
1351 newfdp->fd_refcnt = 1;
1352 spin_init(&newfdp->fd_spin);
1355 * If the number of open files fits in the internal arrays
1356 * of the open file structure, use them, otherwise allocate
1357 * additional memory for the number of descriptors currently
1360 if (newfdp->fd_lastfile < NDFILE) {
1361 newfdp->fd_files = newfdp->fd_builtin_files;
1365 * Compute the smallest file table size
1366 * for the file descriptors currently in use,
1367 * allowing the table to shrink.
1369 i = newfdp->fd_nfiles;
1370 while ((i-1)/2 > newfdp->fd_lastfile && (i-1)/2 > NDFILE)
1372 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1373 M_FILEDESC, M_WAITOK);
1375 newfdp->fd_nfiles = i;
1377 if (fdp->fd_files != fdp->fd_builtin_files ||
1378 newfdp->fd_files != newfdp->fd_builtin_files
1380 bcopy(fdp->fd_files, newfdp->fd_files,
1381 i * sizeof(struct fdnode));
1385 * kq descriptors cannot be copied.
1387 if (newfdp->fd_knlistsize != -1) {
1388 fdnode = &newfdp->fd_files[newfdp->fd_lastfile];
1389 for (i = newfdp->fd_lastfile; i >= 0; i--, fdnode--) {
1390 if (fdnode->fp != NULL && fdnode->fp->f_type == DTYPE_KQUEUE)
1391 funsetfd(newfdp, i); /* nulls out *fpp */
1392 if (fdnode->fp == NULL && i == newfdp->fd_lastfile && i > 0)
1393 newfdp->fd_lastfile--;
1395 newfdp->fd_knlist = NULL;
1396 newfdp->fd_knlistsize = -1;
1397 newfdp->fd_knhash = NULL;
1398 newfdp->fd_knhashmask = 0;
1401 fdnode = newfdp->fd_files;
1402 for (i = newfdp->fd_lastfile; i-- >= 0; fdnode++) {
1403 if (fdnode->fp != NULL)
1410 * Release a filedesc structure.
1413 fdfree(struct proc *p)
1415 struct thread *td = p->p_thread;
1416 struct filedesc *fdp = p->p_fd;
1417 struct fdnode *fdnode;
1419 struct filedesc_to_leader *fdtol;
1424 /* Certain daemons might not have file descriptors. */
1428 /* Check for special need to clear POSIX style locks */
1430 if (fdtol != NULL) {
1431 KASSERT(fdtol->fdl_refcount > 0,
1432 ("filedesc_to_refcount botch: fdl_refcount=%d",
1433 fdtol->fdl_refcount));
1434 if (fdtol->fdl_refcount == 1 &&
1435 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1437 fdnode = fdp->fd_files;
1438 for (i = 0; i <= fdp->fd_lastfile; i++, fdnode++) {
1439 if (fdnode->fp == NULL ||
1440 fdnode->fp->f_type != DTYPE_VNODE)
1444 lf.l_whence = SEEK_SET;
1447 lf.l_type = F_UNLCK;
1448 vp = (struct vnode *)fp->f_data;
1449 (void) VOP_ADVLOCK(vp,
1450 (caddr_t)p->p_leader,
1455 /* reload due to possible reallocation */
1456 fdnode = &fdp->fd_files[i];
1460 if (fdtol->fdl_refcount == 1) {
1461 if (fdp->fd_holdleaderscount > 0 &&
1462 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1464 * close() or do_dup() has cleared a reference
1465 * in a shared file descriptor table.
1467 fdp->fd_holdleaderswakeup = 1;
1468 tsleep(&fdp->fd_holdleaderscount,
1472 if (fdtol->fdl_holdcount > 0) {
1474 * Ensure that fdtol->fdl_leader
1475 * remains valid in closef().
1477 fdtol->fdl_wakeup = 1;
1478 tsleep(fdtol, 0, "fdlhold", 0);
1482 fdtol->fdl_refcount--;
1483 if (fdtol->fdl_refcount == 0 &&
1484 fdtol->fdl_holdcount == 0) {
1485 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1486 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1491 free(fdtol, M_FILEDESC_TO_LEADER);
1493 if (--fdp->fd_refcnt > 0)
1496 * we are the last reference to the structure, we can
1497 * safely assume it will not change out from under us.
1499 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1500 if (fdp->fd_files[i].fp)
1501 closef(fdp->fd_files[i].fp, td);
1503 if (fdp->fd_files != fdp->fd_builtin_files)
1504 free(fdp->fd_files, M_FILEDESC);
1506 cache_drop(fdp->fd_ncdir);
1507 vrele(fdp->fd_cdir);
1510 cache_drop(fdp->fd_nrdir);
1511 vrele(fdp->fd_rdir);
1514 cache_drop(fdp->fd_njdir);
1515 vrele(fdp->fd_jdir);
1518 free(fdp->fd_knlist, M_KQUEUE);
1520 free(fdp->fd_knhash, M_KQUEUE);
1521 free(fdp, M_FILEDESC);
1525 * Retrieve and reference the file pointer associated with a descriptor.
1530 holdfp(struct filedesc *fdp, int fd, int flag)
1534 spin_lock_rd(&fdp->fd_spin);
1535 if (((u_int)fd) >= fdp->fd_nfiles) {
1539 if ((fp = fdp->fd_files[fd].fp) == NULL)
1541 if ((fp->f_flag & flag) == 0 && flag != -1) {
1547 spin_unlock_rd(&fdp->fd_spin);
1552 * holdsock() - load the struct file pointer associated
1553 * with a socket into *fpp. If an error occurs, non-zero
1554 * will be returned and *fpp will be set to NULL.
1557 holdsock(struct filedesc *fdp, int fdes, struct file **fpp)
1563 if ((unsigned)fdes >= fdp->fd_nfiles)
1565 if ((fp = fdp->fd_files[fdes].fp) == NULL)
1567 if (fp->f_type != DTYPE_SOCKET)
1575 * Convert a user file descriptor to a kernel file entry.
1578 getvnode(struct filedesc *fdp, int fd, struct file **fpp)
1582 if ((u_int)fd >= fdp->fd_nfiles ||
1583 (fp = fdp->fd_files[fd].fp) == NULL)
1585 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO)
1592 * For setugid programs, we don't want to people to use that setugidness
1593 * to generate error messages which write to a file which otherwise would
1594 * otherwise be off-limits to the process.
1596 * This is a gross hack to plug the hole. A better solution would involve
1597 * a special vop or other form of generalized access control mechanism. We
1598 * go ahead and just reject all procfs file systems accesses as dangerous.
1600 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1601 * sufficient. We also don't for check setugidness since we know we are.
1604 is_unsafe(struct file *fp)
1606 if (fp->f_type == DTYPE_VNODE &&
1607 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1613 * Make this setguid thing safe, if at all possible.
1616 setugidsafety(struct proc *p)
1618 struct thread *td = p->p_thread;
1619 struct filedesc *fdp = p->p_fd;
1622 /* Certain daemons might not have file descriptors. */
1627 * note: fdp->fd_files may be reallocated out from under us while
1628 * we are blocked in a close. Be careful!
1630 for (i = 0; i <= fdp->fd_lastfile; i++) {
1633 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1636 if (i < fdp->fd_knlistsize)
1637 knote_fdclose(p, i);
1639 * NULL-out descriptor prior to close to avoid
1640 * a race while close blocks.
1642 fp = fdp->fd_files[i].fp;
1647 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1652 * Close any files on exec?
1655 fdcloseexec(struct proc *p)
1657 struct thread *td = p->p_thread;
1658 struct filedesc *fdp = p->p_fd;
1661 /* Certain daemons might not have file descriptors. */
1666 * We cannot cache fd_files since operations may block and rip
1667 * them out from under us.
1669 for (i = 0; i <= fdp->fd_lastfile; i++) {
1670 if (fdp->fd_files[i].fp != NULL &&
1671 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1674 if (i < fdp->fd_knlistsize)
1675 knote_fdclose(p, i);
1677 * NULL-out descriptor prior to close to avoid
1678 * a race while close blocks.
1680 fp = fdp->fd_files[i].fp;
1685 while (fdp->fd_lastfile > 0 && fdp->fd_files[fdp->fd_lastfile].fp == NULL)
1690 * It is unsafe for set[ug]id processes to be started with file
1691 * descriptors 0..2 closed, as these descriptors are given implicit
1692 * significance in the Standard C library. fdcheckstd() will create a
1693 * descriptor referencing /dev/null for each of stdin, stdout, and
1694 * stderr that is not already open.
1697 fdcheckstd(struct proc *p)
1699 struct nlookupdata nd;
1700 struct filedesc *fdp;
1703 int fd, i, error, flags, devnull;
1710 for (i = 0; i < 3; i++) {
1711 if (fdp->fd_files[i].fp != NULL)
1714 if ((error = falloc(p, &fp, NULL)) != 0)
1717 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1718 NLC_FOLLOW|NLC_LOCKVP);
1719 flags = FREAD | FWRITE;
1721 error = vn_open(&nd, fp, flags, 0);
1723 error = fsetfd(p, fp, &fd);
1731 error = kern_dup(DUP_FIXED, devnull, i, &retval);
1740 * Internal form of close.
1741 * Decrement reference count on file structure.
1742 * Note: td and/or p may be NULL when closing a file
1743 * that was being passed in a message.
1746 closef(struct file *fp, struct thread *td)
1750 struct filedesc_to_leader *fdtol;
1757 p = NULL; /* allow no proc association */
1759 p = td->td_proc; /* can also be NULL */
1762 * POSIX record locking dictates that any close releases ALL
1763 * locks owned by this process. This is handled by setting
1764 * a flag in the unlock to free ONLY locks obeying POSIX
1765 * semantics, and not to free BSD-style file locks.
1766 * If the descriptor was in a message, POSIX-style locks
1767 * aren't passed with the descriptor.
1770 fp->f_type == DTYPE_VNODE) {
1771 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
1772 lf.l_whence = SEEK_SET;
1775 lf.l_type = F_UNLCK;
1776 vp = (struct vnode *)fp->f_data;
1777 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
1781 if (fdtol != NULL) {
1783 * Handle special case where file descriptor table
1784 * is shared between multiple process leaders.
1786 for (fdtol = fdtol->fdl_next;
1787 fdtol != p->p_fdtol;
1788 fdtol = fdtol->fdl_next) {
1789 if ((fdtol->fdl_leader->p_flag &
1792 fdtol->fdl_holdcount++;
1793 lf.l_whence = SEEK_SET;
1796 lf.l_type = F_UNLCK;
1797 vp = (struct vnode *)fp->f_data;
1798 (void) VOP_ADVLOCK(vp,
1799 (caddr_t)fdtol->fdl_leader,
1800 F_UNLCK, &lf, F_POSIX);
1801 fdtol->fdl_holdcount--;
1802 if (fdtol->fdl_holdcount == 0 &&
1803 fdtol->fdl_wakeup != 0) {
1804 fdtol->fdl_wakeup = 0;
1816 * fhold() can only be called if f_count is already at least 1 (i.e. the
1817 * caller of fhold() already has a reference to the file pointer in some
1818 * manner or other). In addition, fhold() must be callable with a spinlock
1819 * held on the governing structure that the caller went through to find the
1823 fhold(struct file *fp)
1825 atomic_add_int(&fp->f_count, 1);
1829 * MPSAFE TODO: VOP_ADVLOCK, fo_close
1831 * A spinlock is required to handle 1->0 transitions on f_count.
1834 fdrop(struct file *fp)
1840 spin_lock_wr(&fp->f_spin);
1841 if (--fp->f_count > 0) {
1842 spin_unlock_wr(&fp->f_spin);
1845 spin_unlock_wr(&fp->f_spin);
1848 * The last reference has gone away, we own the fp structure free
1851 if (fp->f_count < 0)
1852 panic("fdrop: count < 0");
1853 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
1854 lf.l_whence = SEEK_SET;
1857 lf.l_type = F_UNLCK;
1858 vp = (struct vnode *)fp->f_data;
1859 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
1861 if (fp->f_ops != &badfileops)
1862 error = fo_close(fp);
1870 * Apply an advisory lock on a file descriptor.
1872 * Just attempt to get a record lock of the requested type on
1873 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
1877 flock(struct flock_args *uap)
1879 struct proc *p = curproc;
1880 struct filedesc *fdp = p->p_fd;
1885 if ((unsigned)uap->fd >= fdp->fd_nfiles ||
1886 (fp = fdp->fd_files[uap->fd].fp) == NULL)
1888 if (fp->f_type != DTYPE_VNODE)
1889 return (EOPNOTSUPP);
1890 vp = (struct vnode *)fp->f_data;
1891 lf.l_whence = SEEK_SET;
1894 if (uap->how & LOCK_UN) {
1895 lf.l_type = F_UNLCK;
1896 fp->f_flag &= ~FHASLOCK;
1897 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0));
1899 if (uap->how & LOCK_EX)
1900 lf.l_type = F_WRLCK;
1901 else if (uap->how & LOCK_SH)
1902 lf.l_type = F_RDLCK;
1905 fp->f_flag |= FHASLOCK;
1906 if (uap->how & LOCK_NB)
1907 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0));
1908 return (VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT));
1912 * File Descriptor pseudo-device driver (/dev/fd/).
1914 * Opening minor device N dup()s the file (if any) connected to file
1915 * descriptor N belonging to the calling process. Note that this driver
1916 * consists of only the ``open()'' routine, because all subsequent
1917 * references to this file will be direct to the other driver.
1921 fdopen(dev_t dev, int mode, int type, struct thread *td)
1923 KKASSERT(td->td_lwp != NULL);
1926 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
1927 * the file descriptor being sought for duplication. The error
1928 * return ensures that the vnode for this device will be released
1929 * by vn_open. Open will detect this special error and take the
1930 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
1931 * will simply report the error.
1933 td->td_lwp->lwp_dupfd = minor(dev);
1938 * Duplicate the specified descriptor to a free descriptor.
1941 dupfdopen(struct filedesc *fdp, int indx, int dfd, int mode, int error)
1947 * If the to-be-dup'd fd number is greater than the allowed number
1948 * of file descriptors, or the fd to be dup'd has already been
1949 * closed, then reject.
1951 if ((u_int)dfd >= fdp->fd_nfiles ||
1952 (wfp = fdp->fd_files[dfd].fp) == NULL) {
1957 * There are two cases of interest here.
1959 * For ENODEV simply dup (dfd) to file descriptor
1960 * (indx) and return.
1962 * For ENXIO steal away the file structure from (dfd) and
1963 * store it in (indx). (dfd) is effectively closed by
1966 * Any other error code is just returned.
1971 * Check that the mode the file is being opened for is a
1972 * subset of the mode of the existing descriptor.
1974 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
1976 fp = fdp->fd_files[indx].fp;
1977 fdp->fd_files[indx].fp = wfp;
1978 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
1980 if (indx > fdp->fd_lastfile)
1981 fdp->fd_lastfile = indx;
1983 * we now own the reference to fp that the ofiles[] array
1984 * used to own. Release it.
1992 * Steal away the file pointer from dfd, and stuff it into indx.
1994 fp = fdp->fd_files[indx].fp;
1995 fdp->fd_files[indx].fp = fdp->fd_files[dfd].fp;
1996 fdp->fd_files[indx].fileflags = fdp->fd_files[dfd].fileflags;
2000 * we now own the reference to fp that the files[] array
2001 * used to own. Release it.
2006 * Complete the clean up of the filedesc structure by
2007 * recomputing the various hints.
2009 if (indx > fdp->fd_lastfile) {
2010 fdp->fd_lastfile = indx;
2012 while (fdp->fd_lastfile > 0 &&
2013 fdp->fd_files[fdp->fd_lastfile].fp == NULL) {
2026 struct filedesc_to_leader *
2027 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2028 struct proc *leader)
2030 struct filedesc_to_leader *fdtol;
2032 fdtol = malloc(sizeof(struct filedesc_to_leader),
2033 M_FILEDESC_TO_LEADER, M_WAITOK);
2034 fdtol->fdl_refcount = 1;
2035 fdtol->fdl_holdcount = 0;
2036 fdtol->fdl_wakeup = 0;
2037 fdtol->fdl_leader = leader;
2039 fdtol->fdl_next = old->fdl_next;
2040 fdtol->fdl_prev = old;
2041 old->fdl_next = fdtol;
2042 fdtol->fdl_next->fdl_prev = fdtol;
2044 fdtol->fdl_next = fdtol;
2045 fdtol->fdl_prev = fdtol;
2051 * Get file structures.
2054 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2056 struct kinfo_file kf;
2057 struct filedesc *fdp;
2066 * Note: because the number of file descriptors is calculated
2067 * in different ways for sizing vs returning the data,
2068 * there is information leakage from the first loop. However,
2069 * it is of a similar order of magnitude to the leakage from
2070 * global system statistics such as kern.openfiles.
2072 * When just doing a count, note that we cannot just count
2073 * the elements and add f_count via the filehead list because
2074 * threaded processes share their descriptor table and f_count might
2075 * still be '1' in that case.
2077 * Since the SYSCTL op can block, we must hold the process to
2078 * prevent it being ripped out from under us either in the
2079 * file descriptor loop or in the greater LIST_FOREACH. The
2080 * process may be in varying states of disrepair. If the process
2081 * is in SZOMB we may have caught it just as it is being removed
2082 * from the allproc list, we must skip it in that case to maintain
2083 * an unbroken chain through the allproc list.
2087 LIST_FOREACH(p, &allproc, p_list) {
2088 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
2090 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
2092 if ((fdp = p->p_fd) == NULL)
2095 for (n = 0; n < fdp->fd_nfiles; ++n) {
2096 if ((fp = fdp->fd_files[n].fp) == NULL)
2098 if (req->oldptr == NULL) {
2101 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2102 kcore_make_file(&kf, fp, p->p_pid, uid, n);
2103 error = SYSCTL_OUT(req, &kf, sizeof(kf));
2114 * When just calculating the size, overestimate a bit to try to
2115 * prevent system activity from causing the buffer-fill call
2118 if (req->oldptr == NULL) {
2119 count = (count + 16) + (count / 10);
2120 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
2125 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2126 0, 0, sysctl_kern_file, "S,file", "Entire file table");
2128 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2129 &maxfilesperproc, 0, "Maximum files allowed open per process");
2131 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2132 &maxfiles, 0, "Maximum number of files");
2134 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
2135 &maxfilesrootres, 0, "Descriptors reserved for root use");
2137 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2138 &nfiles, 0, "System-wide number of open files");
2141 fildesc_drvinit(void *unused)
2145 cdevsw_add(&fildesc_cdevsw, 0, 0);
2146 for (fd = 0; fd < NUMFDESC; fd++) {
2147 make_dev(&fildesc_cdevsw, fd,
2148 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2150 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2151 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2152 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2155 struct fileops badfileops = {
2179 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2185 badfo_poll(struct file *fp, int events, struct ucred *cred)
2191 badfo_kqfilter(struct file *fp, struct knote *kn)
2197 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2203 badfo_close(struct file *fp)
2209 badfo_shutdown(struct file *fp, int how)
2215 nofo_shutdown(struct file *fp, int how)
2217 return (EOPNOTSUPP);
2220 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2221 fildesc_drvinit,NULL)