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.62 2006/05/24 03:23:31 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 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd);
107 static void fdreserve_locked (struct filedesc *fdp, int fd0, int incr);
108 static struct file *funsetfd_locked (struct filedesc *fdp, int fd);
109 static int checkfpclosed(struct filedesc *fdp, int fd, struct file *fp);
110 static void ffree(struct file *fp);
112 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
113 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
114 "file desc to leader structures");
115 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
116 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
118 static d_open_t fdopen;
121 #define CDEV_MAJOR 22
122 static struct cdevsw fildesc_cdevsw = {
124 /* maj */ CDEV_MAJOR,
136 /* strategy */ nostrategy,
141 static int badfo_readwrite (struct file *fp, struct uio *uio,
142 struct ucred *cred, int flags);
143 static int badfo_ioctl (struct file *fp, u_long com, caddr_t data,
145 static int badfo_poll (struct file *fp, int events, struct ucred *cred);
146 static int badfo_kqfilter (struct file *fp, struct knote *kn);
147 static int badfo_stat (struct file *fp, struct stat *sb, struct ucred *cred);
148 static int badfo_close (struct file *fp);
149 static int badfo_shutdown (struct file *fp, int how);
152 * Descriptor management.
154 struct filelist filehead; /* head of list of open files */
155 int nfiles; /* actual number of open files */
159 * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
161 * MPSAFE - must be called with fdp->fd_spin exclusively held
165 fdfixup_locked(struct filedesc *fdp, int fd)
167 if (fd < fdp->fd_freefile) {
168 fdp->fd_freefile = fd;
170 while (fdp->fd_lastfile >= 0 &&
171 fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
172 fdp->fd_files[fdp->fd_lastfile].reserved == 0
179 * System calls on descriptors.
184 getdtablesize(struct getdtablesize_args *uap)
186 struct proc *p = curproc;
187 struct plimit *limit = p->p_limit;
189 spin_lock_rd(&limit->p_spin);
191 min((int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
192 spin_unlock_rd(&limit->p_spin);
197 * Duplicate a file descriptor to a particular value.
199 * note: keep in mind that a potential race condition exists when closing
200 * descriptors from a shared descriptor table (via rfork).
205 dup2(struct dup2_args *uap)
209 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
215 * Duplicate a file descriptor.
220 dup(struct dup_args *uap)
224 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
230 * MPALMOSTSAFE - acquires mplock for fp operations
233 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
235 struct thread *td = curthread;
236 struct proc *p = td->td_proc;
240 int tmp, error, flg = F_POSIX;
245 * Operations on file descriptors that do not require a file pointer.
249 error = fgetfdflags(p->p_fd, fd, &tmp);
251 dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
255 if (dat->fc_cloexec & FD_CLOEXEC)
256 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
258 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
262 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
269 * Operations on file pointers
271 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
277 dat->fc_flags = OFLAGS(fp->f_flag);
282 fp->f_flag &= ~FCNTLFLAGS;
283 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
284 tmp = fp->f_flag & FNONBLOCK;
285 error = fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
288 tmp = fp->f_flag & FASYNC;
289 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
292 fp->f_flag &= ~FNONBLOCK;
294 fo_ioctl(fp, FIONBIO, (caddr_t)&tmp, cred);
298 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
302 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
307 /* Fall into F_SETLK */
310 if (fp->f_type != DTYPE_VNODE) {
314 vp = (struct vnode *)fp->f_data;
317 * copyin/lockop may block
319 if (dat->fc_flock.l_whence == SEEK_CUR)
320 dat->fc_flock.l_start += fp->f_offset;
322 switch (dat->fc_flock.l_type) {
324 if ((fp->f_flag & FREAD) == 0) {
328 p->p_leader->p_flag |= P_ADVLOCK;
329 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
330 &dat->fc_flock, flg);
333 if ((fp->f_flag & FWRITE) == 0) {
337 p->p_leader->p_flag |= P_ADVLOCK;
338 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
339 &dat->fc_flock, flg);
342 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
343 &dat->fc_flock, F_POSIX);
351 * It is possible to race a close() on the descriptor while
352 * we were blocked getting the lock. If this occurs the
353 * close might not have caught the lock.
355 if (checkfpclosed(p->p_fd, fd, fp)) {
356 dat->fc_flock.l_whence = SEEK_SET;
357 dat->fc_flock.l_start = 0;
358 dat->fc_flock.l_len = 0;
359 dat->fc_flock.l_type = F_UNLCK;
360 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
361 F_UNLCK, &dat->fc_flock, F_POSIX);
366 if (fp->f_type != DTYPE_VNODE) {
370 vp = (struct vnode *)fp->f_data;
372 * copyin/lockop may block
374 if (dat->fc_flock.l_type != F_RDLCK &&
375 dat->fc_flock.l_type != F_WRLCK &&
376 dat->fc_flock.l_type != F_UNLCK) {
380 if (dat->fc_flock.l_whence == SEEK_CUR)
381 dat->fc_flock.l_start += fp->f_offset;
382 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
383 &dat->fc_flock, F_POSIX);
396 * The file control system call.
401 fcntl(struct fcntl_args *uap)
408 dat.fc_fd = uap->arg;
411 dat.fc_cloexec = uap->arg;
414 dat.fc_flags = uap->arg;
417 dat.fc_owner = uap->arg;
422 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
423 sizeof(struct flock));
429 error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
434 uap->sysmsg_result = dat.fc_fd;
437 uap->sysmsg_result = dat.fc_cloexec;
440 uap->sysmsg_result = dat.fc_flags;
443 uap->sysmsg_result = dat.fc_owner;
445 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
446 sizeof(struct flock));
455 * Common code for dup, dup2, and fcntl(F_DUPFD).
457 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
458 * kern_dup() to destructively dup over an existing file descriptor if new
459 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
460 * unused file descriptor that is greater than or equal to new.
465 kern_dup(enum dup_type type, int old, int new, int *res)
467 struct thread *td = curthread;
468 struct proc *p = td->td_proc;
469 struct filedesc *fdp = p->p_fd;
477 * Verify that we have a valid descriptor to dup from and
478 * possibly to dup to.
481 spin_lock_wr(&fdp->fd_spin);
482 if (new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
483 new >= maxfilesperproc) {
484 spin_unlock_wr(&fdp->fd_spin);
487 if ((unsigned)old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL) {
488 spin_unlock_wr(&fdp->fd_spin);
491 if (type == DUP_FIXED && old == new) {
493 spin_unlock_wr(&fdp->fd_spin);
496 fp = fdp->fd_files[old].fp;
497 oldflags = fdp->fd_files[old].fileflags;
498 fhold(fp); /* MPSAFE - can be called with a spinlock held */
501 * Allocate a new descriptor if DUP_VARIABLE, or expand the table
502 * if the requested descriptor is beyond the current table size.
504 * This can block. Retry if the source descriptor no longer matches
505 * or if our expectation in the expansion case races.
507 * If we are not expanding or allocating a new decriptor, then reset
508 * the target descriptor to a reserved state so we have a uniform
509 * setup for the next code block.
511 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
512 spin_unlock_wr(&fdp->fd_spin);
513 error = fdalloc(p, new, &newfd);
514 spin_lock_wr(&fdp->fd_spin);
516 spin_unlock_wr(&fdp->fd_spin);
523 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
524 fsetfd_locked(fdp, NULL, newfd);
525 spin_unlock_wr(&fdp->fd_spin);
530 * Check for expansion race
532 if (type != DUP_VARIABLE && new != newfd) {
533 fsetfd_locked(fdp, NULL, newfd);
534 spin_unlock_wr(&fdp->fd_spin);
539 * Check for ripout, newfd reused old (this case probably
543 fsetfd_locked(fdp, NULL, newfd);
544 spin_unlock_wr(&fdp->fd_spin);
551 if (fdp->fd_files[new].reserved) {
552 spin_unlock_wr(&fdp->fd_spin);
554 printf("Warning: dup(): target descriptor %d is reserved, waiting for it to be resolved\n", new);
555 tsleep(fdp, 0, "fdres", hz);
560 * If the target descriptor was never allocated we have
561 * to allocate it. If it was we have to clean out the
562 * old descriptor. delfp inherits the ref from the
565 delfp = fdp->fd_files[new].fp;
566 fdp->fd_files[new].fp = NULL;
567 fdp->fd_files[new].reserved = 1;
569 fdreserve_locked(fdp, new, 1);
570 if (new > fdp->fd_lastfile)
571 fdp->fd_lastfile = new;
577 * NOTE: still holding an exclusive spinlock
581 * If a descriptor is being overwritten we may hve to tell
582 * fdfree() to sleep to ensure that all relevant process
583 * leaders can be traversed in closef().
585 if (delfp != NULL && p->p_fdtol != NULL) {
586 fdp->fd_holdleaderscount++;
591 KASSERT(delfp == NULL || type == DUP_FIXED,
592 ("dup() picked an open file"));
595 * Duplicate the source descriptor, update lastfile. If the new
596 * descriptor was not allocated and we aren't replacing an existing
597 * descriptor we have to mark the descriptor as being in use.
599 * The fd_files[] array inherits fp's hold reference.
601 fsetfd_locked(fdp, fp, new);
602 fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
603 spin_unlock_wr(&fdp->fd_spin);
608 * If we dup'd over a valid file, we now own the reference to it
609 * and must dispose of it using closef() semantics (as if a
610 * close() were performed on it).
613 (void)closef(delfp, td);
615 spin_lock_wr(&fdp->fd_spin);
616 fdp->fd_holdleaderscount--;
617 if (fdp->fd_holdleaderscount == 0 &&
618 fdp->fd_holdleaderswakeup != 0) {
619 fdp->fd_holdleaderswakeup = 0;
620 spin_unlock_wr(&fdp->fd_spin);
621 wakeup(&fdp->fd_holdleaderscount);
623 spin_unlock_wr(&fdp->fd_spin);
631 * If sigio is on the list associated with a process or process group,
632 * disable signalling from the device, remove sigio from the list and
636 funsetown(struct sigio *sigio)
641 *(sigio->sio_myref) = NULL;
643 if (sigio->sio_pgid < 0) {
644 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
646 } else /* if ((*sigiop)->sio_pgid > 0) */ {
647 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
650 crfree(sigio->sio_ucred);
651 free(sigio, M_SIGIO);
654 /* Free a list of sigio structures. */
656 funsetownlst(struct sigiolst *sigiolst)
660 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
665 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
667 * After permission checking, add a sigio structure to the sigio list for
668 * the process or process group.
671 fsetown(pid_t pgid, struct sigio **sigiop)
687 * Policy - Don't allow a process to FSETOWN a process
688 * in another session.
690 * Remove this test to allow maximum flexibility or
691 * restrict FSETOWN to the current process or process
692 * group for maximum safety.
694 if (proc->p_session != curproc->p_session)
698 } else /* if (pgid < 0) */ {
699 pgrp = pgfind(-pgid);
704 * Policy - Don't allow a process to FSETOWN a process
705 * in another session.
707 * Remove this test to allow maximum flexibility or
708 * restrict FSETOWN to the current process or process
709 * group for maximum safety.
711 if (pgrp->pg_session != curproc->p_session)
717 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
719 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
720 sigio->sio_proc = proc;
722 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
723 sigio->sio_pgrp = pgrp;
725 sigio->sio_pgid = pgid;
726 sigio->sio_ucred = crhold(curproc->p_ucred);
727 /* It would be convenient if p_ruid was in ucred. */
728 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
729 sigio->sio_myref = sigiop;
737 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
740 fgetown(struct sigio *sigio)
742 return (sigio != NULL ? sigio->sio_pgid : 0);
746 * Close many file descriptors.
751 closefrom(struct closefrom_args *uap)
753 return(kern_closefrom(uap->fd));
757 * Close all file descriptors greater then or equal to fd
762 kern_closefrom(int fd)
764 struct thread *td = curthread;
765 struct proc *p = td->td_proc;
766 struct filedesc *fdp;
775 * NOTE: This function will skip unassociated descriptors and
776 * reserved descriptors that have not yet been assigned.
777 * fd_lastfile can change as a side effect of kern_close().
779 spin_lock_wr(&fdp->fd_spin);
780 while (fd <= fdp->fd_lastfile) {
781 if (fdp->fd_files[fd].fp != NULL) {
782 spin_unlock_wr(&fdp->fd_spin);
783 /* ok if this races another close */
784 if (kern_close(fd) == EINTR)
786 spin_lock_wr(&fdp->fd_spin);
790 spin_unlock_wr(&fdp->fd_spin);
795 * Close a file descriptor.
800 close(struct close_args *uap)
802 return(kern_close(uap->fd));
806 * MPALMOSTSAFE - acquires mplock around knote_fdclose() calls
811 struct thread *td = curthread;
812 struct proc *p = td->td_proc;
813 struct filedesc *fdp;
821 spin_lock_wr(&fdp->fd_spin);
822 if ((fp = funsetfd_locked(fdp, fd)) == NULL) {
823 spin_unlock_wr(&fdp->fd_spin);
827 if (p->p_fdtol != NULL) {
829 * Ask fdfree() to sleep to ensure that all relevant
830 * process leaders can be traversed in closef().
832 fdp->fd_holdleaderscount++;
837 * we now hold the fp reference that used to be owned by the descriptor
840 spin_unlock_wr(&fdp->fd_spin);
841 if (fd < fdp->fd_knlistsize) {
843 knote_fdclose(p, fd);
846 error = closef(fp, td);
848 spin_lock_wr(&fdp->fd_spin);
849 fdp->fd_holdleaderscount--;
850 if (fdp->fd_holdleaderscount == 0 &&
851 fdp->fd_holdleaderswakeup != 0) {
852 fdp->fd_holdleaderswakeup = 0;
853 spin_unlock_wr(&fdp->fd_spin);
854 wakeup(&fdp->fd_holdleaderscount);
856 spin_unlock_wr(&fdp->fd_spin);
863 * shutdown_args(int fd, int how)
866 kern_shutdown(int fd, int how)
868 struct thread *td = curthread;
869 struct proc *p = td->td_proc;
875 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
877 error = fo_shutdown(fp, how);
884 shutdown(struct shutdown_args *uap)
888 error = kern_shutdown(uap->s, uap->how);
894 kern_fstat(int fd, struct stat *ub)
896 struct thread *td = curthread;
897 struct proc *p = td->td_proc;
903 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
905 error = fo_stat(fp, ub, p->p_ucred);
912 * Return status information about a file descriptor.
915 fstat(struct fstat_args *uap)
920 error = kern_fstat(uap->fd, &st);
923 error = copyout(&st, uap->sb, sizeof(st));
928 * Return pathconf information about a file descriptor.
932 fpathconf(struct fpathconf_args *uap)
934 struct thread *td = curthread;
935 struct proc *p = td->td_proc;
942 if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
945 switch (fp->f_type) {
948 if (uap->name != _PC_PIPE_BUF) {
951 uap->sysmsg_result = PIPE_BUF;
957 vp = (struct vnode *)fp->f_data;
958 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
969 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
972 * Grow the file table so it can hold through descriptor (want).
974 * The fdp's spinlock must be held exclusively on entry and may be held
975 * exclusively on return. The spinlock may be cycled by the routine.
980 fdgrow_locked(struct filedesc *fdp, int want)
982 struct fdnode *newfiles;
983 struct fdnode *oldfiles;
988 /* nf has to be of the form 2^n - 1 */
990 } while (nf <= want);
992 spin_unlock_wr(&fdp->fd_spin);
993 newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
994 spin_lock_wr(&fdp->fd_spin);
997 * We could have raced another extend while we were not holding
1000 if (fdp->fd_nfiles >= nf) {
1001 spin_unlock_wr(&fdp->fd_spin);
1002 free(newfiles, M_FILEDESC);
1003 spin_lock_wr(&fdp->fd_spin);
1007 * Copy the existing ofile and ofileflags arrays
1008 * and zero the new portion of each array.
1010 extra = nf - fdp->fd_nfiles;
1011 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1012 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1014 oldfiles = fdp->fd_files;
1015 fdp->fd_files = newfiles;
1016 fdp->fd_nfiles = nf;
1018 if (oldfiles != fdp->fd_builtin_files) {
1019 spin_unlock_wr(&fdp->fd_spin);
1020 free(oldfiles, M_FILEDESC);
1021 spin_lock_wr(&fdp->fd_spin);
1027 * Number of nodes in right subtree, including the root.
1030 right_subtree_size(int n)
1032 return (n ^ (n | (n + 1)));
1039 right_ancestor(int n)
1041 return (n | (n + 1));
1048 left_ancestor(int n)
1050 return ((n & (n + 1)) - 1);
1054 * Traverse the in-place binary tree buttom-up adjusting the allocation
1055 * count so scans can determine where free descriptors are located.
1057 * MPSAFE - caller must be holding an exclusive spinlock on fdp
1061 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1064 fdp->fd_files[fd].allocated += incr;
1065 KKASSERT(fdp->fd_files[fd].allocated >= 0);
1066 fd = left_ancestor(fd);
1071 * Reserve a file descriptor for the process. If no error occurs, the
1072 * caller MUST at some point call fsetfd() or assign a file pointer
1073 * or dispose of the reservation.
1078 fdalloc(struct proc *p, int want, int *result)
1080 struct filedesc *fdp = p->p_fd;
1081 int fd, rsize, rsum, node, lim;
1083 spin_lock_rd(&p->p_limit->p_spin);
1084 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1085 spin_unlock_rd(&p->p_limit->p_spin);
1088 spin_lock_wr(&fdp->fd_spin);
1089 if (want >= fdp->fd_nfiles)
1090 fdgrow_locked(fdp, want);
1093 * Search for a free descriptor starting at the higher
1094 * of want or fd_freefile. If that fails, consider
1095 * expanding the ofile array.
1097 * NOTE! the 'allocated' field is a cumulative recursive allocation
1098 * count. If we happen to see a value of 0 then we can shortcut
1099 * our search. Otherwise we run through through the tree going
1100 * down branches we know have free descriptor(s) until we hit a
1101 * leaf node. The leaf node will be free but will not necessarily
1102 * have an allocated field of 0.
1105 /* move up the tree looking for a subtree with a free node */
1106 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1107 fd = right_ancestor(fd)) {
1108 if (fdp->fd_files[fd].allocated == 0)
1111 rsize = right_subtree_size(fd);
1112 if (fdp->fd_files[fd].allocated == rsize)
1113 continue; /* right subtree full */
1116 * Free fd is in the right subtree of the tree rooted at fd.
1117 * Call that subtree R. Look for the smallest (leftmost)
1118 * subtree of R with an unallocated fd: continue moving
1119 * down the left branch until encountering a full left
1120 * subtree, then move to the right.
1122 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1124 rsum += fdp->fd_files[node].allocated;
1125 if (fdp->fd_files[fd].allocated == rsum + rsize) {
1126 fd = node; /* move to the right */
1127 if (fdp->fd_files[node].allocated == 0)
1136 * No space in current array. Expand?
1138 if (fdp->fd_nfiles >= lim) {
1139 spin_unlock_wr(&fdp->fd_spin);
1142 fdgrow_locked(fdp, want);
1146 KKASSERT(fd < fdp->fd_nfiles);
1147 if (fd > fdp->fd_lastfile)
1148 fdp->fd_lastfile = fd;
1149 if (want <= fdp->fd_freefile)
1150 fdp->fd_freefile = fd;
1152 KKASSERT(fdp->fd_files[fd].fp == NULL);
1153 KKASSERT(fdp->fd_files[fd].reserved == 0);
1154 fdp->fd_files[fd].fileflags = 0;
1155 fdp->fd_files[fd].reserved = 1;
1156 fdreserve_locked(fdp, fd, 1);
1157 spin_unlock_wr(&fdp->fd_spin);
1162 * Check to see whether n user file descriptors
1163 * are available to the process p.
1168 fdavail(struct proc *p, int n)
1170 struct filedesc *fdp = p->p_fd;
1171 struct fdnode *fdnode;
1174 spin_lock_rd(&p->p_limit->p_spin);
1175 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1176 spin_unlock_rd(&p->p_limit->p_spin);
1178 spin_lock_rd(&fdp->fd_spin);
1179 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1180 spin_unlock_rd(&fdp->fd_spin);
1183 last = min(fdp->fd_nfiles, lim);
1184 fdnode = &fdp->fd_files[fdp->fd_freefile];
1185 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1186 if (fdnode->fp == NULL && --n <= 0) {
1187 spin_unlock_rd(&fdp->fd_spin);
1191 spin_unlock_rd(&fdp->fd_spin);
1197 * Create a new open file structure and reserve a file decriptor
1198 * for the process that refers to it.
1200 * Root creds are checked using p, or assumed if p is NULL. If
1201 * resultfd is non-NULL then p must also be non-NULL. No file
1202 * descriptor is reserved if resultfd is NULL.
1204 * A file pointer with a refcount of 1 is returned. Note that the
1205 * file pointer is NOT associated with the descriptor. If falloc
1206 * returns success, fsetfd() MUST be called to either associate the
1207 * file pointer or clear the reservation.
1209 * NOT MPSAFE (MPUNSAFE) - crhold()
1212 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1214 static struct timeval lastfail;
1222 * Handle filetable full issues and root overfill.
1224 if (nfiles >= maxfiles - maxfilesrootres &&
1225 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1226 if (ppsratecheck(&lastfail, &curfail, 1)) {
1227 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1228 (p ? p->p_ucred->cr_ruid : -1));
1235 * Allocate a new file descriptor.
1238 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1239 spin_init(&fp->f_spin);
1241 fp->f_ops = &badfileops;
1244 fp->f_cred = crhold(p->p_ucred);
1246 fp->f_cred = crhold(proc0.p_ucred);
1247 LIST_INSERT_HEAD(&filehead, fp, f_list);
1249 if ((error = fdalloc(p, 0, resultfd)) != 0) {
1266 checkfpclosed(struct filedesc *fdp, int fd, struct file *fp)
1270 spin_lock_rd(&fdp->fd_spin);
1271 if ((unsigned) fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
1275 spin_unlock_rd(&fdp->fd_spin);
1280 * Associate a file pointer with a previously reserved file descriptor.
1281 * This function always succeeds.
1283 * If fp is NULL, the file descriptor is returned to the pool.
1287 * MPSAFE (exclusive spinlock must be held on call)
1290 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd)
1292 KKASSERT((unsigned)fd < fdp->fd_nfiles);
1293 KKASSERT(fdp->fd_files[fd].reserved != 0);
1296 fdp->fd_files[fd].fp = fp;
1297 fdp->fd_files[fd].reserved = 0;
1299 fdp->fd_files[fd].reserved = 0;
1300 fdreserve_locked(fdp, fd, -1);
1301 fdfixup_locked(fdp, fd);
1309 fsetfd(struct proc *p, struct file *fp, int fd)
1311 struct filedesc *fdp = p->p_fd;
1313 spin_lock_wr(&fdp->fd_spin);
1314 fsetfd_locked(fdp, fp, fd);
1315 spin_unlock_wr(&fdp->fd_spin);
1319 * MPSAFE (exclusive spinlock must be held on call)
1323 funsetfd_locked(struct filedesc *fdp, int fd)
1327 if ((unsigned)fd >= fdp->fd_nfiles)
1329 if ((fp = fdp->fd_files[fd].fp) == NULL)
1331 fdp->fd_files[fd].fp = NULL;
1332 fdp->fd_files[fd].fileflags = 0;
1334 fdreserve_locked(fdp, fd, -1);
1335 fdfixup_locked(fdp, fd);
1343 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1347 spin_lock_rd(&fdp->fd_spin);
1348 if (((u_int)fd) >= fdp->fd_nfiles) {
1350 } else if (fdp->fd_files[fd].fp == NULL) {
1353 *flagsp = fdp->fd_files[fd].fileflags;
1356 spin_unlock_rd(&fdp->fd_spin);
1364 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1368 spin_lock_wr(&fdp->fd_spin);
1369 if (((u_int)fd) >= fdp->fd_nfiles) {
1371 } else if (fdp->fd_files[fd].fp == NULL) {
1374 fdp->fd_files[fd].fileflags |= add_flags;
1377 spin_unlock_wr(&fdp->fd_spin);
1385 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1389 spin_lock_wr(&fdp->fd_spin);
1390 if (((u_int)fd) >= fdp->fd_nfiles) {
1392 } else if (fdp->fd_files[fd].fp == NULL) {
1395 fdp->fd_files[fd].fileflags &= ~rem_flags;
1398 spin_unlock_wr(&fdp->fd_spin);
1403 fsetcred(struct file *fp, struct ucred *cr)
1411 * Free a file descriptor.
1415 ffree(struct file *fp)
1417 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1418 LIST_REMOVE(fp, f_list);
1421 cache_drop(fp->f_ncp);
1429 * called from init_main, initialize filedesc0 for proc0.
1432 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1436 fdp0->fd_refcnt = 1;
1437 fdp0->fd_cmask = cmask;
1438 fdp0->fd_files = fdp0->fd_builtin_files;
1439 fdp0->fd_nfiles = NDFILE;
1440 fdp0->fd_lastfile = -1;
1441 spin_init(&fdp0->fd_spin);
1445 * Build a new filedesc structure.
1450 fdinit(struct proc *p)
1452 struct filedesc *newfdp;
1453 struct filedesc *fdp = p->p_fd;
1455 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1456 spin_lock_rd(&fdp->fd_spin);
1458 newfdp->fd_cdir = fdp->fd_cdir;
1459 vref(newfdp->fd_cdir);
1460 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1464 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1465 * proc0, but should unconditionally exist in other processes.
1468 newfdp->fd_rdir = fdp->fd_rdir;
1469 vref(newfdp->fd_rdir);
1470 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1473 newfdp->fd_jdir = fdp->fd_jdir;
1474 vref(newfdp->fd_jdir);
1475 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1477 spin_unlock_rd(&fdp->fd_spin);
1479 /* Create the file descriptor table. */
1480 newfdp->fd_refcnt = 1;
1481 newfdp->fd_cmask = cmask;
1482 newfdp->fd_files = newfdp->fd_builtin_files;
1483 newfdp->fd_nfiles = NDFILE;
1484 newfdp->fd_knlistsize = -1;
1485 newfdp->fd_lastfile = -1;
1486 spin_init(&newfdp->fd_spin);
1492 * Share a filedesc structure.
1497 fdshare(struct proc *p)
1499 struct filedesc *fdp;
1502 spin_lock_wr(&fdp->fd_spin);
1504 spin_unlock_wr(&fdp->fd_spin);
1509 * Copy a filedesc structure.
1514 fdcopy(struct proc *p)
1516 struct filedesc *fdp = p->p_fd;
1517 struct filedesc *newfdp;
1518 struct fdnode *fdnode;
1523 * Certain daemons might not have file descriptors.
1529 * Allocate the new filedesc and fd_files[] array. This can race
1530 * with operations by other threads on the fdp so we have to be
1533 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK | M_ZERO);
1535 spin_lock_rd(&fdp->fd_spin);
1536 if (fdp->fd_lastfile < NDFILE) {
1537 newfdp->fd_files = newfdp->fd_builtin_files;
1541 * We have to allocate (N^2-1) entries for our in-place
1542 * binary tree. Allow the table to shrink.
1546 while (ni > fdp->fd_lastfile && ni > NDFILE) {
1550 spin_unlock_rd(&fdp->fd_spin);
1551 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1552 M_FILEDESC, M_WAITOK | M_ZERO);
1555 * Check for race, retry
1557 spin_lock_rd(&fdp->fd_spin);
1558 if (i <= fdp->fd_lastfile) {
1559 spin_unlock_rd(&fdp->fd_spin);
1560 free(newfdp->fd_files, M_FILEDESC);
1566 * Dup the remaining fields. vref() and cache_hold() can be
1567 * safely called while holding the read spinlock on fdp.
1569 * The read spinlock on fdp is still being held.
1571 * NOTE: vref and cache_hold calls for the case where the vnode
1572 * or cache entry already has at least one ref may be called
1573 * while holding spin locks.
1575 if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
1576 vref(newfdp->fd_cdir);
1577 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1580 * We must check for fd_rdir here, at least for now because
1581 * the init process is created before we have access to the
1582 * rootvode to take a reference to it.
1584 if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
1585 vref(newfdp->fd_rdir);
1586 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1588 if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
1589 vref(newfdp->fd_jdir);
1590 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1592 newfdp->fd_refcnt = 1;
1593 newfdp->fd_nfiles = i;
1594 newfdp->fd_lastfile = fdp->fd_lastfile;
1595 newfdp->fd_freefile = fdp->fd_freefile;
1596 newfdp->fd_cmask = fdp->fd_cmask;
1597 newfdp->fd_knlist = NULL;
1598 newfdp->fd_knlistsize = -1;
1599 newfdp->fd_knhash = NULL;
1600 newfdp->fd_knhashmask = 0;
1601 spin_init(&newfdp->fd_spin);
1604 * Copy the descriptor table through (i). This also copies the
1605 * allocation state. Then go through and ref the file pointers
1606 * and clean up any KQ descriptors.
1608 * kq descriptors cannot be copied. Since we haven't ref'd the
1609 * copied files yet we can ignore the return value from funsetfd().
1611 * The read spinlock on fdp is still being held.
1613 bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
1614 for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
1615 fdnode = &newfdp->fd_files[i];
1616 if (fdnode->reserved) {
1617 fdreserve_locked(newfdp, i, -1);
1618 fdnode->reserved = 0;
1619 fdfixup_locked(newfdp, i);
1620 } else if (fdnode->fp) {
1621 if (fdnode->fp->f_type == DTYPE_KQUEUE) {
1622 (void)funsetfd_locked(newfdp, i);
1628 spin_unlock_rd(&fdp->fd_spin);
1633 * Release a filedesc structure.
1635 * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
1638 fdfree(struct proc *p)
1640 struct thread *td = p->p_thread;
1641 struct filedesc *fdp = p->p_fd;
1642 struct fdnode *fdnode;
1644 struct filedesc_to_leader *fdtol;
1649 /* Certain daemons might not have file descriptors. */
1654 * Severe messing around to follow
1656 spin_lock_wr(&fdp->fd_spin);
1658 /* Check for special need to clear POSIX style locks */
1660 if (fdtol != NULL) {
1661 KASSERT(fdtol->fdl_refcount > 0,
1662 ("filedesc_to_refcount botch: fdl_refcount=%d",
1663 fdtol->fdl_refcount));
1664 if (fdtol->fdl_refcount == 1 &&
1665 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1666 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1667 fdnode = &fdp->fd_files[i];
1668 if (fdnode->fp == NULL ||
1669 fdnode->fp->f_type != DTYPE_VNODE) {
1674 spin_unlock_wr(&fdp->fd_spin);
1676 lf.l_whence = SEEK_SET;
1679 lf.l_type = F_UNLCK;
1680 vp = (struct vnode *)fp->f_data;
1681 (void) VOP_ADVLOCK(vp,
1682 (caddr_t)p->p_leader,
1687 spin_lock_wr(&fdp->fd_spin);
1691 if (fdtol->fdl_refcount == 1) {
1692 if (fdp->fd_holdleaderscount > 0 &&
1693 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1695 * close() or do_dup() has cleared a reference
1696 * in a shared file descriptor table.
1698 fdp->fd_holdleaderswakeup = 1;
1699 spin_unlock_wr(&fdp->fd_spin);
1700 tsleep(&fdp->fd_holdleaderscount,
1702 spin_lock_wr(&fdp->fd_spin);
1705 if (fdtol->fdl_holdcount > 0) {
1707 * Ensure that fdtol->fdl_leader
1708 * remains valid in closef().
1710 fdtol->fdl_wakeup = 1;
1711 spin_unlock_wr(&fdp->fd_spin);
1712 tsleep(fdtol, 0, "fdlhold", 0);
1713 spin_lock_wr(&fdp->fd_spin);
1717 fdtol->fdl_refcount--;
1718 if (fdtol->fdl_refcount == 0 &&
1719 fdtol->fdl_holdcount == 0) {
1720 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1721 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1726 if (fdtol != NULL) {
1727 spin_unlock_wr(&fdp->fd_spin);
1728 free(fdtol, M_FILEDESC_TO_LEADER);
1729 spin_lock_wr(&fdp->fd_spin);
1732 if (--fdp->fd_refcnt > 0) {
1733 spin_unlock_wr(&fdp->fd_spin);
1736 spin_unlock_wr(&fdp->fd_spin);
1739 * we are the last reference to the structure, we can
1740 * safely assume it will not change out from under us.
1742 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1743 if (fdp->fd_files[i].fp)
1744 closef(fdp->fd_files[i].fp, td);
1746 if (fdp->fd_files != fdp->fd_builtin_files)
1747 free(fdp->fd_files, M_FILEDESC);
1749 cache_drop(fdp->fd_ncdir);
1750 vrele(fdp->fd_cdir);
1753 cache_drop(fdp->fd_nrdir);
1754 vrele(fdp->fd_rdir);
1757 cache_drop(fdp->fd_njdir);
1758 vrele(fdp->fd_jdir);
1761 free(fdp->fd_knlist, M_KQUEUE);
1763 free(fdp->fd_knhash, M_KQUEUE);
1764 free(fdp, M_FILEDESC);
1768 * Retrieve and reference the file pointer associated with a descriptor.
1773 holdfp(struct filedesc *fdp, int fd, int flag)
1777 spin_lock_rd(&fdp->fd_spin);
1778 if (((u_int)fd) >= fdp->fd_nfiles) {
1782 if ((fp = fdp->fd_files[fd].fp) == NULL)
1784 if ((fp->f_flag & flag) == 0 && flag != -1) {
1790 spin_unlock_rd(&fdp->fd_spin);
1795 * holdsock() - load the struct file pointer associated
1796 * with a socket into *fpp. If an error occurs, non-zero
1797 * will be returned and *fpp will be set to NULL.
1802 holdsock(struct filedesc *fdp, int fd, struct file **fpp)
1807 spin_lock_rd(&fdp->fd_spin);
1808 if ((unsigned)fd >= fdp->fd_nfiles) {
1813 if ((fp = fdp->fd_files[fd].fp) == NULL) {
1817 if (fp->f_type != DTYPE_SOCKET) {
1824 spin_unlock_rd(&fdp->fd_spin);
1830 * Convert a user file descriptor to a held file pointer.
1835 holdvnode(struct filedesc *fdp, int fd, struct file **fpp)
1840 spin_lock_rd(&fdp->fd_spin);
1841 if ((unsigned)fd >= fdp->fd_nfiles) {
1846 if ((fp = fdp->fd_files[fd].fp) == NULL) {
1850 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
1857 spin_unlock_rd(&fdp->fd_spin);
1863 * For setugid programs, we don't want to people to use that setugidness
1864 * to generate error messages which write to a file which otherwise would
1865 * otherwise be off-limits to the process.
1867 * This is a gross hack to plug the hole. A better solution would involve
1868 * a special vop or other form of generalized access control mechanism. We
1869 * go ahead and just reject all procfs file systems accesses as dangerous.
1871 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1872 * sufficient. We also don't for check setugidness since we know we are.
1875 is_unsafe(struct file *fp)
1877 if (fp->f_type == DTYPE_VNODE &&
1878 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1884 * Make this setguid thing safe, if at all possible.
1886 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1889 setugidsafety(struct proc *p)
1891 struct thread *td = p->p_thread;
1892 struct filedesc *fdp = p->p_fd;
1895 /* Certain daemons might not have file descriptors. */
1900 * note: fdp->fd_files may be reallocated out from under us while
1901 * we are blocked in a close. Be careful!
1903 for (i = 0; i <= fdp->fd_lastfile; i++) {
1906 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1909 if (i < fdp->fd_knlistsize)
1910 knote_fdclose(p, i);
1912 * NULL-out descriptor prior to close to avoid
1913 * a race while close blocks.
1915 if ((fp = funsetfd_locked(fdp, i)) != NULL)
1922 * Close any files on exec?
1924 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1927 fdcloseexec(struct proc *p)
1929 struct thread *td = p->p_thread;
1930 struct filedesc *fdp = p->p_fd;
1933 /* Certain daemons might not have file descriptors. */
1938 * We cannot cache fd_files since operations may block and rip
1939 * them out from under us.
1941 for (i = 0; i <= fdp->fd_lastfile; i++) {
1942 if (fdp->fd_files[i].fp != NULL &&
1943 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1946 if (i < fdp->fd_knlistsize)
1947 knote_fdclose(p, i);
1949 * NULL-out descriptor prior to close to avoid
1950 * a race while close blocks.
1952 if ((fp = funsetfd_locked(fdp, i)) != NULL)
1959 * It is unsafe for set[ug]id processes to be started with file
1960 * descriptors 0..2 closed, as these descriptors are given implicit
1961 * significance in the Standard C library. fdcheckstd() will create a
1962 * descriptor referencing /dev/null for each of stdin, stdout, and
1963 * stderr that is not already open.
1965 * NOT MPSAFE - calls falloc, vn_open, etc
1968 fdcheckstd(struct proc *p)
1970 struct nlookupdata nd;
1971 struct filedesc *fdp;
1974 int i, error, flags, devnull;
1981 for (i = 0; i < 3; i++) {
1982 if (fdp->fd_files[i].fp != NULL)
1985 if ((error = falloc(p, &fp, &devnull)) != 0)
1988 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1989 NLC_FOLLOW|NLC_LOCKVP);
1990 flags = FREAD | FWRITE;
1992 error = vn_open(&nd, fp, flags, 0);
1994 fsetfd(p, fp, devnull);
1996 fsetfd(p, NULL, devnull);
2001 KKASSERT(i == devnull);
2003 error = kern_dup(DUP_FIXED, devnull, i, &retval);
2012 * Internal form of close.
2013 * Decrement reference count on file structure.
2014 * Note: td and/or p may be NULL when closing a file
2015 * that was being passed in a message.
2017 * MPALMOSTSAFE - acquires mplock for VOP operations
2020 closef(struct file *fp, struct thread *td)
2024 struct filedesc_to_leader *fdtol;
2031 p = NULL; /* allow no proc association */
2033 p = td->td_proc; /* can also be NULL */
2037 * POSIX record locking dictates that any close releases ALL
2038 * locks owned by this process. This is handled by setting
2039 * a flag in the unlock to free ONLY locks obeying POSIX
2040 * semantics, and not to free BSD-style file locks.
2041 * If the descriptor was in a message, POSIX-style locks
2042 * aren't passed with the descriptor.
2045 fp->f_type == DTYPE_VNODE) {
2046 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
2047 lf.l_whence = SEEK_SET;
2050 lf.l_type = F_UNLCK;
2051 vp = (struct vnode *)fp->f_data;
2052 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2056 if (fdtol != NULL) {
2058 * Handle special case where file descriptor table
2059 * is shared between multiple process leaders.
2061 for (fdtol = fdtol->fdl_next;
2062 fdtol != p->p_fdtol;
2063 fdtol = fdtol->fdl_next) {
2064 if ((fdtol->fdl_leader->p_flag &
2067 fdtol->fdl_holdcount++;
2068 lf.l_whence = SEEK_SET;
2071 lf.l_type = F_UNLCK;
2072 vp = (struct vnode *)fp->f_data;
2073 (void) VOP_ADVLOCK(vp,
2074 (caddr_t)fdtol->fdl_leader,
2075 F_UNLCK, &lf, F_POSIX);
2076 fdtol->fdl_holdcount--;
2077 if (fdtol->fdl_holdcount == 0 &&
2078 fdtol->fdl_wakeup != 0) {
2079 fdtol->fdl_wakeup = 0;
2092 * fhold() can only be called if f_count is already at least 1 (i.e. the
2093 * caller of fhold() already has a reference to the file pointer in some
2096 * This is a rare case where callers are allowed to hold spinlocks, so
2097 * we can't ourselves. Since we are not obtaining the fp spinlock,
2098 * we have to use an atomic lock to interlock against fdrop().
2101 fhold(struct file *fp)
2103 atomic_add_int(&fp->f_count, 1);
2107 * A spinlock is required to handle 1->0 transitions on f_count. We have
2108 * to use atomic_sub_int so as not to race the atomic_add_int in fhold().
2110 * MPALMOSTSAFE - acquires mplock for final close sequence
2113 fdrop(struct file *fp)
2119 spin_lock_wr(&fp->f_spin);
2120 atomic_subtract_int(&fp->f_count, 1);
2121 if (fp->f_count > 0) {
2122 spin_unlock_wr(&fp->f_spin);
2125 spin_unlock_wr(&fp->f_spin);
2130 * The last reference has gone away, we own the fp structure free
2133 if (fp->f_count < 0)
2134 panic("fdrop: count < 0");
2135 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE) {
2136 lf.l_whence = SEEK_SET;
2139 lf.l_type = F_UNLCK;
2140 vp = (struct vnode *)fp->f_data;
2141 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2143 if (fp->f_ops != &badfileops)
2144 error = fo_close(fp);
2153 * Apply an advisory lock on a file descriptor.
2155 * Just attempt to get a record lock of the requested type on
2156 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2159 flock(struct flock_args *uap)
2161 struct proc *p = curproc;
2167 if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
2169 if (fp->f_type != DTYPE_VNODE) {
2173 vp = (struct vnode *)fp->f_data;
2174 lf.l_whence = SEEK_SET;
2177 if (uap->how & LOCK_UN) {
2178 lf.l_type = F_UNLCK;
2179 fp->f_flag &= ~FHASLOCK;
2180 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2183 if (uap->how & LOCK_EX)
2184 lf.l_type = F_WRLCK;
2185 else if (uap->how & LOCK_SH)
2186 lf.l_type = F_RDLCK;
2191 fp->f_flag |= FHASLOCK;
2192 if (uap->how & LOCK_NB)
2193 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0);
2195 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT);
2202 * File Descriptor pseudo-device driver (/dev/fd/).
2204 * Opening minor device N dup()s the file (if any) connected to file
2205 * descriptor N belonging to the calling process. Note that this driver
2206 * consists of only the ``open()'' routine, because all subsequent
2207 * references to this file will be direct to the other driver.
2211 fdopen(dev_t dev, int mode, int type, struct thread *td)
2213 KKASSERT(td->td_lwp != NULL);
2216 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
2217 * the file descriptor being sought for duplication. The error
2218 * return ensures that the vnode for this device will be released
2219 * by vn_open. Open will detect this special error and take the
2220 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2221 * will simply report the error.
2223 td->td_lwp->lwp_dupfd = minor(dev);
2228 * The caller has reserved the file descriptor dfd for us. On success we
2229 * must fsetfd() it. On failure the caller will clean it up.
2231 * NOT MPSAFE - isn't getting spinlocks, possibly other things
2234 dupfdopen(struct proc *p, int dfd, int sfd, int mode, int error)
2236 struct filedesc *fdp = p->p_fd;
2240 if ((wfp = holdfp(fdp, sfd, -1)) == NULL)
2244 * There are two cases of interest here.
2246 * For ENODEV simply dup sfd to file descriptor dfd and return.
2248 * For ENXIO steal away the file structure from sfd and store it
2249 * dfd. sfd is effectively closed by this operation.
2251 * Any other error code is just returned.
2256 * Check that the mode the file is being opened for is a
2257 * subset of the mode of the existing descriptor.
2259 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
2261 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2262 fsetfd(p, wfp, dfd);
2267 * Steal away the file pointer from dfd, and stuff it into indx.
2269 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2270 fsetfd(p, wfp, dfd);
2271 if ((xfp = funsetfd_locked(fdp, sfd)) != NULL)
2273 KKASSERT(xfp == wfp); /* XXX MP RACE */
2284 * NOT MPSAFE - I think these refer to a common file descriptor table
2285 * and we need to spinlock that to link fdtol in.
2287 struct filedesc_to_leader *
2288 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2289 struct proc *leader)
2291 struct filedesc_to_leader *fdtol;
2293 fdtol = malloc(sizeof(struct filedesc_to_leader),
2294 M_FILEDESC_TO_LEADER, M_WAITOK);
2295 fdtol->fdl_refcount = 1;
2296 fdtol->fdl_holdcount = 0;
2297 fdtol->fdl_wakeup = 0;
2298 fdtol->fdl_leader = leader;
2300 fdtol->fdl_next = old->fdl_next;
2301 fdtol->fdl_prev = old;
2302 old->fdl_next = fdtol;
2303 fdtol->fdl_next->fdl_prev = fdtol;
2305 fdtol->fdl_next = fdtol;
2306 fdtol->fdl_prev = fdtol;
2312 * Get file structures.
2314 * NOT MPSAFE - process list scan, SYSCTL_OUT (probably not mpsafe)
2317 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2319 struct kinfo_file kf;
2320 struct filedesc *fdp;
2329 * Note: because the number of file descriptors is calculated
2330 * in different ways for sizing vs returning the data,
2331 * there is information leakage from the first loop. However,
2332 * it is of a similar order of magnitude to the leakage from
2333 * global system statistics such as kern.openfiles.
2335 * When just doing a count, note that we cannot just count
2336 * the elements and add f_count via the filehead list because
2337 * threaded processes share their descriptor table and f_count might
2338 * still be '1' in that case.
2340 * Since the SYSCTL op can block, we must hold the process to
2341 * prevent it being ripped out from under us either in the
2342 * file descriptor loop or in the greater LIST_FOREACH. The
2343 * process may be in varying states of disrepair. If the process
2344 * is in SZOMB we may have caught it just as it is being removed
2345 * from the allproc list, we must skip it in that case to maintain
2346 * an unbroken chain through the allproc list.
2350 LIST_FOREACH(p, &allproc, p_list) {
2351 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
2353 if (!PRISON_CHECK(req->td->td_proc->p_ucred, p->p_ucred) != 0)
2355 if ((fdp = p->p_fd) == NULL)
2358 spin_lock_rd(&fdp->fd_spin);
2359 for (n = 0; n < fdp->fd_nfiles; ++n) {
2360 if ((fp = fdp->fd_files[n].fp) == NULL)
2362 if (req->oldptr == NULL) {
2365 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2366 kcore_make_file(&kf, fp, p->p_pid, uid, n);
2367 spin_unlock_rd(&fdp->fd_spin);
2368 error = SYSCTL_OUT(req, &kf, sizeof(kf));
2369 spin_lock_rd(&fdp->fd_spin);
2374 spin_unlock_rd(&fdp->fd_spin);
2381 * When just calculating the size, overestimate a bit to try to
2382 * prevent system activity from causing the buffer-fill call
2385 if (req->oldptr == NULL) {
2386 count = (count + 16) + (count / 10);
2387 error = SYSCTL_OUT(req, NULL, count * sizeof(kf));
2392 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2393 0, 0, sysctl_kern_file, "S,file", "Entire file table");
2395 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2396 &maxfilesperproc, 0, "Maximum files allowed open per process");
2398 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2399 &maxfiles, 0, "Maximum number of files");
2401 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
2402 &maxfilesrootres, 0, "Descriptors reserved for root use");
2404 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2405 &nfiles, 0, "System-wide number of open files");
2408 fildesc_drvinit(void *unused)
2412 cdevsw_add(&fildesc_cdevsw, 0, 0);
2413 for (fd = 0; fd < NUMFDESC; fd++) {
2414 make_dev(&fildesc_cdevsw, fd,
2415 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2417 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2418 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2419 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2422 struct fileops badfileops = {
2446 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2452 badfo_poll(struct file *fp, int events, struct ucred *cred)
2458 badfo_kqfilter(struct file *fp, struct knote *kn)
2464 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2470 badfo_close(struct file *fp)
2476 badfo_shutdown(struct file *fp, int how)
2482 nofo_shutdown(struct file *fp, int how)
2484 return (EOPNOTSUPP);
2487 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2488 fildesc_drvinit,NULL)