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.68 2006/06/13 08:12:03 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 static struct filelist filehead = LIST_HEAD_INITIALIZER(&filehead);
155 static struct spinlock filehead_spin = SPINLOCK_INITIALIZER(&filehead_spin);
156 static int nfiles; /* actual number of open files */
160 * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
162 * MPSAFE - must be called with fdp->fd_spin exclusively held
166 fdfixup_locked(struct filedesc *fdp, int fd)
168 if (fd < fdp->fd_freefile) {
169 fdp->fd_freefile = fd;
171 while (fdp->fd_lastfile >= 0 &&
172 fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
173 fdp->fd_files[fdp->fd_lastfile].reserved == 0
180 * System calls on descriptors.
185 sys_getdtablesize(struct getdtablesize_args *uap)
187 struct proc *p = curproc;
188 struct plimit *limit = p->p_limit;
190 spin_lock_rd(&limit->p_spin);
192 min((int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
193 spin_unlock_rd(&limit->p_spin);
198 * Duplicate a file descriptor to a particular value.
200 * note: keep in mind that a potential race condition exists when closing
201 * descriptors from a shared descriptor table (via rfork).
206 sys_dup2(struct dup2_args *uap)
210 error = kern_dup(DUP_FIXED, uap->from, uap->to, uap->sysmsg_fds);
216 * Duplicate a file descriptor.
221 sys_dup(struct dup_args *uap)
225 error = kern_dup(DUP_VARIABLE, uap->fd, 0, uap->sysmsg_fds);
231 * MPALMOSTSAFE - acquires mplock for fp operations
234 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
236 struct thread *td = curthread;
237 struct proc *p = td->td_proc;
242 int tmp, error, flg = F_POSIX;
247 * Operations on file descriptors that do not require a file pointer.
251 error = fgetfdflags(p->p_fd, fd, &tmp);
253 dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
257 if (dat->fc_cloexec & FD_CLOEXEC)
258 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
260 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
264 error = kern_dup(DUP_VARIABLE, fd, newmin, &dat->fc_fd);
271 * Operations on file pointers
273 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
279 dat->fc_flags = OFLAGS(fp->f_flag);
284 oflags = fp->f_flag & FCNTLFLAGS;
285 fp->f_flag &= ~FCNTLFLAGS;
286 fp->f_flag |= FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
287 tmp = fp->f_flag & FASYNC;
288 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp, cred);
291 fp->f_flag = (fp->f_flag & ~FCNTLFLAGS) | oflags;
295 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner, cred);
299 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner, cred);
304 /* Fall into F_SETLK */
307 if (fp->f_type != DTYPE_VNODE) {
311 vp = (struct vnode *)fp->f_data;
314 * copyin/lockop may block
316 if (dat->fc_flock.l_whence == SEEK_CUR)
317 dat->fc_flock.l_start += fp->f_offset;
319 switch (dat->fc_flock.l_type) {
321 if ((fp->f_flag & FREAD) == 0) {
325 p->p_leader->p_flag |= P_ADVLOCK;
326 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
327 &dat->fc_flock, flg);
330 if ((fp->f_flag & FWRITE) == 0) {
334 p->p_leader->p_flag |= P_ADVLOCK;
335 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
336 &dat->fc_flock, flg);
339 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
340 &dat->fc_flock, F_POSIX);
348 * It is possible to race a close() on the descriptor while
349 * we were blocked getting the lock. If this occurs the
350 * close might not have caught the lock.
352 if (checkfpclosed(p->p_fd, fd, fp)) {
353 dat->fc_flock.l_whence = SEEK_SET;
354 dat->fc_flock.l_start = 0;
355 dat->fc_flock.l_len = 0;
356 dat->fc_flock.l_type = F_UNLCK;
357 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
358 F_UNLCK, &dat->fc_flock, F_POSIX);
363 if (fp->f_type != DTYPE_VNODE) {
367 vp = (struct vnode *)fp->f_data;
369 * copyin/lockop may block
371 if (dat->fc_flock.l_type != F_RDLCK &&
372 dat->fc_flock.l_type != F_WRLCK &&
373 dat->fc_flock.l_type != F_UNLCK) {
377 if (dat->fc_flock.l_whence == SEEK_CUR)
378 dat->fc_flock.l_start += fp->f_offset;
379 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
380 &dat->fc_flock, F_POSIX);
393 * The file control system call.
398 sys_fcntl(struct fcntl_args *uap)
405 dat.fc_fd = uap->arg;
408 dat.fc_cloexec = uap->arg;
411 dat.fc_flags = uap->arg;
414 dat.fc_owner = uap->arg;
419 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
420 sizeof(struct flock));
426 error = kern_fcntl(uap->fd, uap->cmd, &dat, curproc->p_ucred);
431 uap->sysmsg_result = dat.fc_fd;
434 uap->sysmsg_result = dat.fc_cloexec;
437 uap->sysmsg_result = dat.fc_flags;
440 uap->sysmsg_result = dat.fc_owner;
442 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
443 sizeof(struct flock));
452 * Common code for dup, dup2, and fcntl(F_DUPFD).
454 * The type flag can be either DUP_FIXED or DUP_VARIABLE. DUP_FIXED tells
455 * kern_dup() to destructively dup over an existing file descriptor if new
456 * is already open. DUP_VARIABLE tells kern_dup() to find the lowest
457 * unused file descriptor that is greater than or equal to new.
462 kern_dup(enum dup_type type, int old, int new, int *res)
464 struct thread *td = curthread;
465 struct proc *p = td->td_proc;
466 struct filedesc *fdp = p->p_fd;
474 * Verify that we have a valid descriptor to dup from and
475 * possibly to dup to.
478 spin_lock_wr(&fdp->fd_spin);
479 if (new < 0 || new > p->p_rlimit[RLIMIT_NOFILE].rlim_cur ||
480 new >= maxfilesperproc) {
481 spin_unlock_wr(&fdp->fd_spin);
484 if ((unsigned)old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL) {
485 spin_unlock_wr(&fdp->fd_spin);
488 if (type == DUP_FIXED && old == new) {
490 spin_unlock_wr(&fdp->fd_spin);
493 fp = fdp->fd_files[old].fp;
494 oldflags = fdp->fd_files[old].fileflags;
495 fhold(fp); /* MPSAFE - can be called with a spinlock held */
498 * Allocate a new descriptor if DUP_VARIABLE, or expand the table
499 * if the requested descriptor is beyond the current table size.
501 * This can block. Retry if the source descriptor no longer matches
502 * or if our expectation in the expansion case races.
504 * If we are not expanding or allocating a new decriptor, then reset
505 * the target descriptor to a reserved state so we have a uniform
506 * setup for the next code block.
508 if (type == DUP_VARIABLE || new >= fdp->fd_nfiles) {
509 spin_unlock_wr(&fdp->fd_spin);
510 error = fdalloc(p, new, &newfd);
511 spin_lock_wr(&fdp->fd_spin);
513 spin_unlock_wr(&fdp->fd_spin);
520 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
521 fsetfd_locked(fdp, NULL, newfd);
522 spin_unlock_wr(&fdp->fd_spin);
527 * Check for expansion race
529 if (type != DUP_VARIABLE && new != newfd) {
530 fsetfd_locked(fdp, NULL, newfd);
531 spin_unlock_wr(&fdp->fd_spin);
536 * Check for ripout, newfd reused old (this case probably
540 fsetfd_locked(fdp, NULL, newfd);
541 spin_unlock_wr(&fdp->fd_spin);
548 if (fdp->fd_files[new].reserved) {
549 spin_unlock_wr(&fdp->fd_spin);
551 printf("Warning: dup(): target descriptor %d is reserved, waiting for it to be resolved\n", new);
552 tsleep(fdp, 0, "fdres", hz);
557 * If the target descriptor was never allocated we have
558 * to allocate it. If it was we have to clean out the
559 * old descriptor. delfp inherits the ref from the
562 delfp = fdp->fd_files[new].fp;
563 fdp->fd_files[new].fp = NULL;
564 fdp->fd_files[new].reserved = 1;
566 fdreserve_locked(fdp, new, 1);
567 if (new > fdp->fd_lastfile)
568 fdp->fd_lastfile = new;
574 * NOTE: still holding an exclusive spinlock
578 * If a descriptor is being overwritten we may hve to tell
579 * fdfree() to sleep to ensure that all relevant process
580 * leaders can be traversed in closef().
582 if (delfp != NULL && p->p_fdtol != NULL) {
583 fdp->fd_holdleaderscount++;
588 KASSERT(delfp == NULL || type == DUP_FIXED,
589 ("dup() picked an open file"));
592 * Duplicate the source descriptor, update lastfile. If the new
593 * descriptor was not allocated and we aren't replacing an existing
594 * descriptor we have to mark the descriptor as being in use.
596 * The fd_files[] array inherits fp's hold reference.
598 fsetfd_locked(fdp, fp, new);
599 fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
600 spin_unlock_wr(&fdp->fd_spin);
605 * If we dup'd over a valid file, we now own the reference to it
606 * and must dispose of it using closef() semantics (as if a
607 * close() were performed on it).
610 (void)closef(delfp, td);
612 spin_lock_wr(&fdp->fd_spin);
613 fdp->fd_holdleaderscount--;
614 if (fdp->fd_holdleaderscount == 0 &&
615 fdp->fd_holdleaderswakeup != 0) {
616 fdp->fd_holdleaderswakeup = 0;
617 spin_unlock_wr(&fdp->fd_spin);
618 wakeup(&fdp->fd_holdleaderscount);
620 spin_unlock_wr(&fdp->fd_spin);
628 * If sigio is on the list associated with a process or process group,
629 * disable signalling from the device, remove sigio from the list and
633 funsetown(struct sigio *sigio)
638 *(sigio->sio_myref) = NULL;
640 if (sigio->sio_pgid < 0) {
641 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
643 } else /* if ((*sigiop)->sio_pgid > 0) */ {
644 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
647 crfree(sigio->sio_ucred);
648 free(sigio, M_SIGIO);
651 /* Free a list of sigio structures. */
653 funsetownlst(struct sigiolst *sigiolst)
657 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
662 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
664 * After permission checking, add a sigio structure to the sigio list for
665 * the process or process group.
668 fsetown(pid_t pgid, struct sigio **sigiop)
684 * Policy - Don't allow a process to FSETOWN a process
685 * in another session.
687 * Remove this test to allow maximum flexibility or
688 * restrict FSETOWN to the current process or process
689 * group for maximum safety.
691 if (proc->p_session != curproc->p_session)
695 } else /* if (pgid < 0) */ {
696 pgrp = pgfind(-pgid);
701 * Policy - Don't allow a process to FSETOWN a process
702 * in another session.
704 * Remove this test to allow maximum flexibility or
705 * restrict FSETOWN to the current process or process
706 * group for maximum safety.
708 if (pgrp->pg_session != curproc->p_session)
714 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
716 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
717 sigio->sio_proc = proc;
719 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
720 sigio->sio_pgrp = pgrp;
722 sigio->sio_pgid = pgid;
723 sigio->sio_ucred = crhold(curproc->p_ucred);
724 /* It would be convenient if p_ruid was in ucred. */
725 sigio->sio_ruid = curproc->p_ucred->cr_ruid;
726 sigio->sio_myref = sigiop;
734 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
737 fgetown(struct sigio *sigio)
739 return (sigio != NULL ? sigio->sio_pgid : 0);
743 * Close many file descriptors.
748 sys_closefrom(struct closefrom_args *uap)
750 return(kern_closefrom(uap->fd));
754 * Close all file descriptors greater then or equal to fd
759 kern_closefrom(int fd)
761 struct thread *td = curthread;
762 struct proc *p = td->td_proc;
763 struct filedesc *fdp;
772 * NOTE: This function will skip unassociated descriptors and
773 * reserved descriptors that have not yet been assigned.
774 * fd_lastfile can change as a side effect of kern_close().
776 spin_lock_wr(&fdp->fd_spin);
777 while (fd <= fdp->fd_lastfile) {
778 if (fdp->fd_files[fd].fp != NULL) {
779 spin_unlock_wr(&fdp->fd_spin);
780 /* ok if this races another close */
781 if (kern_close(fd) == EINTR)
783 spin_lock_wr(&fdp->fd_spin);
787 spin_unlock_wr(&fdp->fd_spin);
792 * Close a file descriptor.
797 sys_close(struct close_args *uap)
799 return(kern_close(uap->fd));
803 * MPALMOSTSAFE - acquires mplock around knote_fdclose() calls
808 struct thread *td = curthread;
809 struct proc *p = td->td_proc;
810 struct filedesc *fdp;
818 spin_lock_wr(&fdp->fd_spin);
819 if ((fp = funsetfd_locked(fdp, fd)) == NULL) {
820 spin_unlock_wr(&fdp->fd_spin);
824 if (p->p_fdtol != NULL) {
826 * Ask fdfree() to sleep to ensure that all relevant
827 * process leaders can be traversed in closef().
829 fdp->fd_holdleaderscount++;
834 * we now hold the fp reference that used to be owned by the descriptor
837 spin_unlock_wr(&fdp->fd_spin);
838 if (fd < fdp->fd_knlistsize) {
840 if (fd < fdp->fd_knlistsize)
841 knote_fdclose(p, fd);
844 error = closef(fp, td);
846 spin_lock_wr(&fdp->fd_spin);
847 fdp->fd_holdleaderscount--;
848 if (fdp->fd_holdleaderscount == 0 &&
849 fdp->fd_holdleaderswakeup != 0) {
850 fdp->fd_holdleaderswakeup = 0;
851 spin_unlock_wr(&fdp->fd_spin);
852 wakeup(&fdp->fd_holdleaderscount);
854 spin_unlock_wr(&fdp->fd_spin);
861 * shutdown_args(int fd, int how)
864 kern_shutdown(int fd, int how)
866 struct thread *td = curthread;
867 struct proc *p = td->td_proc;
873 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
875 error = fo_shutdown(fp, how);
882 sys_shutdown(struct shutdown_args *uap)
886 error = kern_shutdown(uap->s, uap->how);
892 kern_fstat(int fd, struct stat *ub)
894 struct thread *td = curthread;
895 struct proc *p = td->td_proc;
901 if ((fp = holdfp(p->p_fd, fd, -1)) == NULL)
903 error = fo_stat(fp, ub, p->p_ucred);
910 * Return status information about a file descriptor.
913 sys_fstat(struct fstat_args *uap)
918 error = kern_fstat(uap->fd, &st);
921 error = copyout(&st, uap->sb, sizeof(st));
926 * Return pathconf information about a file descriptor.
930 sys_fpathconf(struct fpathconf_args *uap)
932 struct thread *td = curthread;
933 struct proc *p = td->td_proc;
940 if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
943 switch (fp->f_type) {
946 if (uap->name != _PC_PIPE_BUF) {
949 uap->sysmsg_result = PIPE_BUF;
955 vp = (struct vnode *)fp->f_data;
956 error = VOP_PATHCONF(vp, uap->name, uap->sysmsg_fds);
967 SYSCTL_INT(_debug, OID_AUTO, fdexpand, CTLFLAG_RD, &fdexpand, 0, "");
970 * Grow the file table so it can hold through descriptor (want).
972 * The fdp's spinlock must be held exclusively on entry and may be held
973 * exclusively on return. The spinlock may be cycled by the routine.
978 fdgrow_locked(struct filedesc *fdp, int want)
980 struct fdnode *newfiles;
981 struct fdnode *oldfiles;
986 /* nf has to be of the form 2^n - 1 */
988 } while (nf <= want);
990 spin_unlock_wr(&fdp->fd_spin);
991 newfiles = malloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
992 spin_lock_wr(&fdp->fd_spin);
995 * We could have raced another extend while we were not holding
998 if (fdp->fd_nfiles >= nf) {
999 spin_unlock_wr(&fdp->fd_spin);
1000 free(newfiles, M_FILEDESC);
1001 spin_lock_wr(&fdp->fd_spin);
1005 * Copy the existing ofile and ofileflags arrays
1006 * and zero the new portion of each array.
1008 extra = nf - fdp->fd_nfiles;
1009 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1010 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1012 oldfiles = fdp->fd_files;
1013 fdp->fd_files = newfiles;
1014 fdp->fd_nfiles = nf;
1016 if (oldfiles != fdp->fd_builtin_files) {
1017 spin_unlock_wr(&fdp->fd_spin);
1018 free(oldfiles, M_FILEDESC);
1019 spin_lock_wr(&fdp->fd_spin);
1025 * Number of nodes in right subtree, including the root.
1028 right_subtree_size(int n)
1030 return (n ^ (n | (n + 1)));
1037 right_ancestor(int n)
1039 return (n | (n + 1));
1046 left_ancestor(int n)
1048 return ((n & (n + 1)) - 1);
1052 * Traverse the in-place binary tree buttom-up adjusting the allocation
1053 * count so scans can determine where free descriptors are located.
1055 * MPSAFE - caller must be holding an exclusive spinlock on fdp
1059 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1062 fdp->fd_files[fd].allocated += incr;
1063 KKASSERT(fdp->fd_files[fd].allocated >= 0);
1064 fd = left_ancestor(fd);
1069 * Reserve a file descriptor for the process. If no error occurs, the
1070 * caller MUST at some point call fsetfd() or assign a file pointer
1071 * or dispose of the reservation.
1076 fdalloc(struct proc *p, int want, int *result)
1078 struct filedesc *fdp = p->p_fd;
1079 int fd, rsize, rsum, node, lim;
1081 spin_lock_rd(&p->p_limit->p_spin);
1082 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1083 spin_unlock_rd(&p->p_limit->p_spin);
1086 spin_lock_wr(&fdp->fd_spin);
1087 if (want >= fdp->fd_nfiles)
1088 fdgrow_locked(fdp, want);
1091 * Search for a free descriptor starting at the higher
1092 * of want or fd_freefile. If that fails, consider
1093 * expanding the ofile array.
1095 * NOTE! the 'allocated' field is a cumulative recursive allocation
1096 * count. If we happen to see a value of 0 then we can shortcut
1097 * our search. Otherwise we run through through the tree going
1098 * down branches we know have free descriptor(s) until we hit a
1099 * leaf node. The leaf node will be free but will not necessarily
1100 * have an allocated field of 0.
1103 /* move up the tree looking for a subtree with a free node */
1104 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1105 fd = right_ancestor(fd)) {
1106 if (fdp->fd_files[fd].allocated == 0)
1109 rsize = right_subtree_size(fd);
1110 if (fdp->fd_files[fd].allocated == rsize)
1111 continue; /* right subtree full */
1114 * Free fd is in the right subtree of the tree rooted at fd.
1115 * Call that subtree R. Look for the smallest (leftmost)
1116 * subtree of R with an unallocated fd: continue moving
1117 * down the left branch until encountering a full left
1118 * subtree, then move to the right.
1120 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1122 rsum += fdp->fd_files[node].allocated;
1123 if (fdp->fd_files[fd].allocated == rsum + rsize) {
1124 fd = node; /* move to the right */
1125 if (fdp->fd_files[node].allocated == 0)
1134 * No space in current array. Expand?
1136 if (fdp->fd_nfiles >= lim) {
1137 spin_unlock_wr(&fdp->fd_spin);
1140 fdgrow_locked(fdp, want);
1144 KKASSERT(fd < fdp->fd_nfiles);
1145 if (fd > fdp->fd_lastfile)
1146 fdp->fd_lastfile = fd;
1147 if (want <= fdp->fd_freefile)
1148 fdp->fd_freefile = fd;
1150 KKASSERT(fdp->fd_files[fd].fp == NULL);
1151 KKASSERT(fdp->fd_files[fd].reserved == 0);
1152 fdp->fd_files[fd].fileflags = 0;
1153 fdp->fd_files[fd].reserved = 1;
1154 fdreserve_locked(fdp, fd, 1);
1155 spin_unlock_wr(&fdp->fd_spin);
1160 * Check to see whether n user file descriptors
1161 * are available to the process p.
1166 fdavail(struct proc *p, int n)
1168 struct filedesc *fdp = p->p_fd;
1169 struct fdnode *fdnode;
1172 spin_lock_rd(&p->p_limit->p_spin);
1173 lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfilesperproc);
1174 spin_unlock_rd(&p->p_limit->p_spin);
1176 spin_lock_rd(&fdp->fd_spin);
1177 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1178 spin_unlock_rd(&fdp->fd_spin);
1181 last = min(fdp->fd_nfiles, lim);
1182 fdnode = &fdp->fd_files[fdp->fd_freefile];
1183 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1184 if (fdnode->fp == NULL && --n <= 0) {
1185 spin_unlock_rd(&fdp->fd_spin);
1189 spin_unlock_rd(&fdp->fd_spin);
1195 * Create a new open file structure and reserve a file decriptor
1196 * for the process that refers to it.
1198 * Root creds are checked using p, or assumed if p is NULL. If
1199 * resultfd is non-NULL then p must also be non-NULL. No file
1200 * descriptor is reserved if resultfd is NULL.
1202 * A file pointer with a refcount of 1 is returned. Note that the
1203 * file pointer is NOT associated with the descriptor. If falloc
1204 * returns success, fsetfd() MUST be called to either associate the
1205 * file pointer or clear the reservation.
1210 falloc(struct proc *p, struct file **resultfp, int *resultfd)
1212 static struct timeval lastfail;
1220 * Handle filetable full issues and root overfill.
1222 if (nfiles >= maxfiles - maxfilesrootres &&
1223 ((p && p->p_ucred->cr_ruid != 0) || nfiles >= maxfiles)) {
1224 if (ppsratecheck(&lastfail, &curfail, 1)) {
1225 printf("kern.maxfiles limit exceeded by uid %d, please see tuning(7).\n",
1226 (p ? p->p_ucred->cr_ruid : -1));
1233 * Allocate a new file descriptor.
1235 fp = malloc(sizeof(struct file), M_FILE, M_WAITOK | M_ZERO);
1236 spin_init(&fp->f_spin);
1238 fp->f_ops = &badfileops;
1241 fp->f_cred = crhold(p->p_ucred);
1243 fp->f_cred = crhold(proc0.p_ucred);
1244 spin_lock_wr(&filehead_spin);
1246 LIST_INSERT_HEAD(&filehead, fp, f_list);
1247 spin_unlock_wr(&filehead_spin);
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;
1298 if (fp->f_type == DTYPE_KQUEUE) {
1299 if (fdp->fd_knlistsize < 0)
1300 fdp->fd_knlistsize = 0;
1303 fdp->fd_files[fd].reserved = 0;
1304 fdreserve_locked(fdp, fd, -1);
1305 fdfixup_locked(fdp, fd);
1313 fsetfd(struct proc *p, struct file *fp, int fd)
1315 struct filedesc *fdp = p->p_fd;
1317 spin_lock_wr(&fdp->fd_spin);
1318 fsetfd_locked(fdp, fp, fd);
1319 spin_unlock_wr(&fdp->fd_spin);
1323 * MPSAFE (exclusive spinlock must be held on call)
1327 funsetfd_locked(struct filedesc *fdp, int fd)
1331 if ((unsigned)fd >= fdp->fd_nfiles)
1333 if ((fp = fdp->fd_files[fd].fp) == NULL)
1335 fdp->fd_files[fd].fp = NULL;
1336 fdp->fd_files[fd].fileflags = 0;
1338 fdreserve_locked(fdp, fd, -1);
1339 fdfixup_locked(fdp, fd);
1347 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
1351 spin_lock_rd(&fdp->fd_spin);
1352 if (((u_int)fd) >= fdp->fd_nfiles) {
1354 } else if (fdp->fd_files[fd].fp == NULL) {
1357 *flagsp = fdp->fd_files[fd].fileflags;
1360 spin_unlock_rd(&fdp->fd_spin);
1368 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
1372 spin_lock_wr(&fdp->fd_spin);
1373 if (((u_int)fd) >= fdp->fd_nfiles) {
1375 } else if (fdp->fd_files[fd].fp == NULL) {
1378 fdp->fd_files[fd].fileflags |= add_flags;
1381 spin_unlock_wr(&fdp->fd_spin);
1389 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
1393 spin_lock_wr(&fdp->fd_spin);
1394 if (((u_int)fd) >= fdp->fd_nfiles) {
1396 } else if (fdp->fd_files[fd].fp == NULL) {
1399 fdp->fd_files[fd].fileflags &= ~rem_flags;
1402 spin_unlock_wr(&fdp->fd_spin);
1407 fsetcred(struct file *fp, struct ucred *cr)
1415 * Free a file descriptor.
1419 ffree(struct file *fp)
1421 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
1422 spin_lock_wr(&filehead_spin);
1423 LIST_REMOVE(fp, f_list);
1425 spin_unlock_wr(&filehead_spin);
1428 cache_drop(fp->f_ncp);
1435 * called from init_main, initialize filedesc0 for proc0.
1438 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
1442 fdp0->fd_refcnt = 1;
1443 fdp0->fd_cmask = cmask;
1444 fdp0->fd_files = fdp0->fd_builtin_files;
1445 fdp0->fd_nfiles = NDFILE;
1446 fdp0->fd_lastfile = -1;
1447 spin_init(&fdp0->fd_spin);
1451 * Build a new filedesc structure.
1456 fdinit(struct proc *p)
1458 struct filedesc *newfdp;
1459 struct filedesc *fdp = p->p_fd;
1461 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
1462 spin_lock_rd(&fdp->fd_spin);
1464 newfdp->fd_cdir = fdp->fd_cdir;
1465 vref(newfdp->fd_cdir);
1466 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1470 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
1471 * proc0, but should unconditionally exist in other processes.
1474 newfdp->fd_rdir = fdp->fd_rdir;
1475 vref(newfdp->fd_rdir);
1476 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1479 newfdp->fd_jdir = fdp->fd_jdir;
1480 vref(newfdp->fd_jdir);
1481 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1483 spin_unlock_rd(&fdp->fd_spin);
1485 /* Create the file descriptor table. */
1486 newfdp->fd_refcnt = 1;
1487 newfdp->fd_cmask = cmask;
1488 newfdp->fd_files = newfdp->fd_builtin_files;
1489 newfdp->fd_nfiles = NDFILE;
1490 newfdp->fd_knlistsize = -1;
1491 newfdp->fd_lastfile = -1;
1492 spin_init(&newfdp->fd_spin);
1498 * Share a filedesc structure.
1503 fdshare(struct proc *p)
1505 struct filedesc *fdp;
1508 spin_lock_wr(&fdp->fd_spin);
1510 spin_unlock_wr(&fdp->fd_spin);
1515 * Copy a filedesc structure.
1520 fdcopy(struct proc *p)
1522 struct filedesc *fdp = p->p_fd;
1523 struct filedesc *newfdp;
1524 struct fdnode *fdnode;
1529 * Certain daemons might not have file descriptors.
1535 * Allocate the new filedesc and fd_files[] array. This can race
1536 * with operations by other threads on the fdp so we have to be
1539 newfdp = malloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK | M_ZERO);
1541 spin_lock_rd(&fdp->fd_spin);
1542 if (fdp->fd_lastfile < NDFILE) {
1543 newfdp->fd_files = newfdp->fd_builtin_files;
1547 * We have to allocate (N^2-1) entries for our in-place
1548 * binary tree. Allow the table to shrink.
1552 while (ni > fdp->fd_lastfile && ni > NDFILE) {
1556 spin_unlock_rd(&fdp->fd_spin);
1557 newfdp->fd_files = malloc(i * sizeof(struct fdnode),
1558 M_FILEDESC, M_WAITOK | M_ZERO);
1561 * Check for race, retry
1563 spin_lock_rd(&fdp->fd_spin);
1564 if (i <= fdp->fd_lastfile) {
1565 spin_unlock_rd(&fdp->fd_spin);
1566 free(newfdp->fd_files, M_FILEDESC);
1572 * Dup the remaining fields. vref() and cache_hold() can be
1573 * safely called while holding the read spinlock on fdp.
1575 * The read spinlock on fdp is still being held.
1577 * NOTE: vref and cache_hold calls for the case where the vnode
1578 * or cache entry already has at least one ref may be called
1579 * while holding spin locks.
1581 if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
1582 vref(newfdp->fd_cdir);
1583 newfdp->fd_ncdir = cache_hold(fdp->fd_ncdir);
1586 * We must check for fd_rdir here, at least for now because
1587 * the init process is created before we have access to the
1588 * rootvode to take a reference to it.
1590 if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
1591 vref(newfdp->fd_rdir);
1592 newfdp->fd_nrdir = cache_hold(fdp->fd_nrdir);
1594 if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
1595 vref(newfdp->fd_jdir);
1596 newfdp->fd_njdir = cache_hold(fdp->fd_njdir);
1598 newfdp->fd_refcnt = 1;
1599 newfdp->fd_nfiles = i;
1600 newfdp->fd_lastfile = fdp->fd_lastfile;
1601 newfdp->fd_freefile = fdp->fd_freefile;
1602 newfdp->fd_cmask = fdp->fd_cmask;
1603 newfdp->fd_knlist = NULL;
1604 newfdp->fd_knlistsize = -1;
1605 newfdp->fd_knhash = NULL;
1606 newfdp->fd_knhashmask = 0;
1607 spin_init(&newfdp->fd_spin);
1610 * Copy the descriptor table through (i). This also copies the
1611 * allocation state. Then go through and ref the file pointers
1612 * and clean up any KQ descriptors.
1614 * kq descriptors cannot be copied. Since we haven't ref'd the
1615 * copied files yet we can ignore the return value from funsetfd().
1617 * The read spinlock on fdp is still being held.
1619 bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
1620 for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
1621 fdnode = &newfdp->fd_files[i];
1622 if (fdnode->reserved) {
1623 fdreserve_locked(newfdp, i, -1);
1624 fdnode->reserved = 0;
1625 fdfixup_locked(newfdp, i);
1626 } else if (fdnode->fp) {
1627 if (fdnode->fp->f_type == DTYPE_KQUEUE) {
1628 (void)funsetfd_locked(newfdp, i);
1634 spin_unlock_rd(&fdp->fd_spin);
1639 * Release a filedesc structure.
1641 * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
1644 fdfree(struct proc *p)
1646 struct thread *td = p->p_thread;
1647 struct filedesc *fdp = p->p_fd;
1648 struct fdnode *fdnode;
1650 struct filedesc_to_leader *fdtol;
1655 /* Certain daemons might not have file descriptors. */
1660 * Severe messing around to follow
1662 spin_lock_wr(&fdp->fd_spin);
1664 /* Check for special need to clear POSIX style locks */
1666 if (fdtol != NULL) {
1667 KASSERT(fdtol->fdl_refcount > 0,
1668 ("filedesc_to_refcount botch: fdl_refcount=%d",
1669 fdtol->fdl_refcount));
1670 if (fdtol->fdl_refcount == 1 &&
1671 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1672 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1673 fdnode = &fdp->fd_files[i];
1674 if (fdnode->fp == NULL ||
1675 fdnode->fp->f_type != DTYPE_VNODE) {
1680 spin_unlock_wr(&fdp->fd_spin);
1682 lf.l_whence = SEEK_SET;
1685 lf.l_type = F_UNLCK;
1686 vp = (struct vnode *)fp->f_data;
1687 (void) VOP_ADVLOCK(vp,
1688 (caddr_t)p->p_leader,
1693 spin_lock_wr(&fdp->fd_spin);
1697 if (fdtol->fdl_refcount == 1) {
1698 if (fdp->fd_holdleaderscount > 0 &&
1699 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1701 * close() or do_dup() has cleared a reference
1702 * in a shared file descriptor table.
1704 fdp->fd_holdleaderswakeup = 1;
1705 msleep(&fdp->fd_holdleaderscount,
1706 &fdp->fd_spin, 0, "fdlhold", 0);
1709 if (fdtol->fdl_holdcount > 0) {
1711 * Ensure that fdtol->fdl_leader
1712 * remains valid in closef().
1714 fdtol->fdl_wakeup = 1;
1715 msleep(fdtol, &fdp->fd_spin, 0, "fdlhold", 0);
1719 fdtol->fdl_refcount--;
1720 if (fdtol->fdl_refcount == 0 &&
1721 fdtol->fdl_holdcount == 0) {
1722 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
1723 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
1728 if (fdtol != NULL) {
1729 spin_unlock_wr(&fdp->fd_spin);
1730 free(fdtol, M_FILEDESC_TO_LEADER);
1731 spin_lock_wr(&fdp->fd_spin);
1734 if (--fdp->fd_refcnt > 0) {
1735 spin_unlock_wr(&fdp->fd_spin);
1738 spin_unlock_wr(&fdp->fd_spin);
1741 * we are the last reference to the structure, we can
1742 * safely assume it will not change out from under us.
1744 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1745 if (fdp->fd_files[i].fp)
1746 closef(fdp->fd_files[i].fp, td);
1748 if (fdp->fd_files != fdp->fd_builtin_files)
1749 free(fdp->fd_files, M_FILEDESC);
1751 cache_drop(fdp->fd_ncdir);
1752 vrele(fdp->fd_cdir);
1755 cache_drop(fdp->fd_nrdir);
1756 vrele(fdp->fd_rdir);
1759 cache_drop(fdp->fd_njdir);
1760 vrele(fdp->fd_jdir);
1763 free(fdp->fd_knlist, M_KQUEUE);
1765 free(fdp->fd_knhash, M_KQUEUE);
1766 free(fdp, M_FILEDESC);
1770 * Retrieve and reference the file pointer associated with a descriptor.
1775 holdfp(struct filedesc *fdp, int fd, int flag)
1779 spin_lock_rd(&fdp->fd_spin);
1780 if (((u_int)fd) >= fdp->fd_nfiles) {
1784 if ((fp = fdp->fd_files[fd].fp) == NULL)
1786 if ((fp->f_flag & flag) == 0 && flag != -1) {
1792 spin_unlock_rd(&fdp->fd_spin);
1797 * holdsock() - load the struct file pointer associated
1798 * with a socket into *fpp. If an error occurs, non-zero
1799 * will be returned and *fpp will be set to NULL.
1804 holdsock(struct filedesc *fdp, int fd, struct file **fpp)
1809 spin_lock_rd(&fdp->fd_spin);
1810 if ((unsigned)fd >= fdp->fd_nfiles) {
1815 if ((fp = fdp->fd_files[fd].fp) == NULL) {
1819 if (fp->f_type != DTYPE_SOCKET) {
1826 spin_unlock_rd(&fdp->fd_spin);
1832 * Convert a user file descriptor to a held file pointer.
1837 holdvnode(struct filedesc *fdp, int fd, struct file **fpp)
1842 spin_lock_rd(&fdp->fd_spin);
1843 if ((unsigned)fd >= fdp->fd_nfiles) {
1848 if ((fp = fdp->fd_files[fd].fp) == NULL) {
1852 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
1859 spin_unlock_rd(&fdp->fd_spin);
1865 * For setugid programs, we don't want to people to use that setugidness
1866 * to generate error messages which write to a file which otherwise would
1867 * otherwise be off-limits to the process.
1869 * This is a gross hack to plug the hole. A better solution would involve
1870 * a special vop or other form of generalized access control mechanism. We
1871 * go ahead and just reject all procfs file systems accesses as dangerous.
1873 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
1874 * sufficient. We also don't for check setugidness since we know we are.
1877 is_unsafe(struct file *fp)
1879 if (fp->f_type == DTYPE_VNODE &&
1880 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
1886 * Make this setguid thing safe, if at all possible.
1888 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1891 setugidsafety(struct proc *p)
1893 struct thread *td = p->p_thread;
1894 struct filedesc *fdp = p->p_fd;
1897 /* Certain daemons might not have file descriptors. */
1902 * note: fdp->fd_files may be reallocated out from under us while
1903 * we are blocked in a close. Be careful!
1905 for (i = 0; i <= fdp->fd_lastfile; i++) {
1908 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
1911 if (i < fdp->fd_knlistsize)
1912 knote_fdclose(p, i);
1914 * NULL-out descriptor prior to close to avoid
1915 * a race while close blocks.
1917 if ((fp = funsetfd_locked(fdp, i)) != NULL)
1924 * Close any files on exec?
1926 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
1929 fdcloseexec(struct proc *p)
1931 struct thread *td = p->p_thread;
1932 struct filedesc *fdp = p->p_fd;
1935 /* Certain daemons might not have file descriptors. */
1940 * We cannot cache fd_files since operations may block and rip
1941 * them out from under us.
1943 for (i = 0; i <= fdp->fd_lastfile; i++) {
1944 if (fdp->fd_files[i].fp != NULL &&
1945 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
1948 if (i < fdp->fd_knlistsize)
1949 knote_fdclose(p, i);
1951 * NULL-out descriptor prior to close to avoid
1952 * a race while close blocks.
1954 if ((fp = funsetfd_locked(fdp, i)) != NULL)
1961 * It is unsafe for set[ug]id processes to be started with file
1962 * descriptors 0..2 closed, as these descriptors are given implicit
1963 * significance in the Standard C library. fdcheckstd() will create a
1964 * descriptor referencing /dev/null for each of stdin, stdout, and
1965 * stderr that is not already open.
1967 * NOT MPSAFE - calls falloc, vn_open, etc
1970 fdcheckstd(struct proc *p)
1972 struct nlookupdata nd;
1973 struct filedesc *fdp;
1976 int i, error, flags, devnull;
1983 for (i = 0; i < 3; i++) {
1984 if (fdp->fd_files[i].fp != NULL)
1987 if ((error = falloc(p, &fp, &devnull)) != 0)
1990 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
1991 NLC_FOLLOW|NLC_LOCKVP);
1992 flags = FREAD | FWRITE;
1994 error = vn_open(&nd, fp, flags, 0);
1996 fsetfd(p, fp, devnull);
1998 fsetfd(p, NULL, devnull);
2003 KKASSERT(i == devnull);
2005 error = kern_dup(DUP_FIXED, devnull, i, &retval);
2014 * Internal form of close.
2015 * Decrement reference count on file structure.
2016 * Note: td and/or p may be NULL when closing a file
2017 * that was being passed in a message.
2019 * MPALMOSTSAFE - acquires mplock for VOP operations
2022 closef(struct file *fp, struct thread *td)
2026 struct filedesc_to_leader *fdtol;
2033 p = NULL; /* allow no proc association */
2035 p = td->td_proc; /* can also be NULL */
2038 * POSIX record locking dictates that any close releases ALL
2039 * locks owned by this process. This is handled by setting
2040 * a flag in the unlock to free ONLY locks obeying POSIX
2041 * semantics, and not to free BSD-style file locks.
2042 * If the descriptor was in a message, POSIX-style locks
2043 * aren't passed with the descriptor.
2045 if (p != NULL && fp->f_type == DTYPE_VNODE &&
2046 (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2049 if ((p->p_leader->p_flag & P_ADVLOCK) != 0) {
2050 lf.l_whence = SEEK_SET;
2053 lf.l_type = F_UNLCK;
2054 vp = (struct vnode *)fp->f_data;
2055 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2059 if (fdtol != NULL) {
2061 * Handle special case where file descriptor table
2062 * is shared between multiple process leaders.
2064 for (fdtol = fdtol->fdl_next;
2065 fdtol != p->p_fdtol;
2066 fdtol = fdtol->fdl_next) {
2067 if ((fdtol->fdl_leader->p_flag &
2070 fdtol->fdl_holdcount++;
2071 lf.l_whence = SEEK_SET;
2074 lf.l_type = F_UNLCK;
2075 vp = (struct vnode *)fp->f_data;
2076 (void) VOP_ADVLOCK(vp,
2077 (caddr_t)fdtol->fdl_leader,
2078 F_UNLCK, &lf, F_POSIX);
2079 fdtol->fdl_holdcount--;
2080 if (fdtol->fdl_holdcount == 0 &&
2081 fdtol->fdl_wakeup != 0) {
2082 fdtol->fdl_wakeup = 0;
2095 * fhold() can only be called if f_count is already at least 1 (i.e. the
2096 * caller of fhold() already has a reference to the file pointer in some
2099 * This is a rare case where callers are allowed to hold spinlocks, so
2100 * we can't ourselves. Since we are not obtaining the fp spinlock,
2101 * we have to use an atomic lock to interlock against fdrop().
2104 fhold(struct file *fp)
2106 atomic_add_int(&fp->f_count, 1);
2110 * A spinlock is required to handle 1->0 transitions on f_count. We have
2111 * to use atomic_sub_int so as not to race the atomic_add_int in fhold().
2113 * MPALMOSTSAFE - acquires mplock for final close sequence
2116 fdrop(struct file *fp)
2122 spin_lock_wr(&fp->f_spin);
2123 atomic_subtract_int(&fp->f_count, 1);
2124 if (fp->f_count > 0) {
2125 spin_unlock_wr(&fp->f_spin);
2128 spin_unlock_wr(&fp->f_spin);
2133 * The last reference has gone away, we own the fp structure free
2136 if (fp->f_count < 0)
2137 panic("fdrop: count < 0");
2138 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE &&
2139 (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2141 lf.l_whence = SEEK_SET;
2144 lf.l_type = F_UNLCK;
2145 vp = (struct vnode *)fp->f_data;
2146 (void) VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2148 if (fp->f_ops != &badfileops)
2149 error = fo_close(fp);
2158 * Apply an advisory lock on a file descriptor.
2160 * Just attempt to get a record lock of the requested type on
2161 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2164 sys_flock(struct flock_args *uap)
2166 struct proc *p = curproc;
2172 if ((fp = holdfp(p->p_fd, uap->fd, -1)) == NULL)
2174 if (fp->f_type != DTYPE_VNODE) {
2178 vp = (struct vnode *)fp->f_data;
2179 lf.l_whence = SEEK_SET;
2182 if (uap->how & LOCK_UN) {
2183 lf.l_type = F_UNLCK;
2184 fp->f_flag &= ~FHASLOCK;
2185 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
2188 if (uap->how & LOCK_EX)
2189 lf.l_type = F_WRLCK;
2190 else if (uap->how & LOCK_SH)
2191 lf.l_type = F_RDLCK;
2196 fp->f_flag |= FHASLOCK;
2197 if (uap->how & LOCK_NB)
2198 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0);
2200 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT);
2207 * File Descriptor pseudo-device driver (/dev/fd/).
2209 * Opening minor device N dup()s the file (if any) connected to file
2210 * descriptor N belonging to the calling process. Note that this driver
2211 * consists of only the ``open()'' routine, because all subsequent
2212 * references to this file will be direct to the other driver.
2216 fdopen(dev_t dev, int mode, int type, struct thread *td)
2218 KKASSERT(td->td_lwp != NULL);
2221 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
2222 * the file descriptor being sought for duplication. The error
2223 * return ensures that the vnode for this device will be released
2224 * by vn_open. Open will detect this special error and take the
2225 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
2226 * will simply report the error.
2228 td->td_lwp->lwp_dupfd = minor(dev);
2233 * The caller has reserved the file descriptor dfd for us. On success we
2234 * must fsetfd() it. On failure the caller will clean it up.
2236 * NOT MPSAFE - isn't getting spinlocks, possibly other things
2239 dupfdopen(struct proc *p, int dfd, int sfd, int mode, int error)
2241 struct filedesc *fdp = p->p_fd;
2245 if ((wfp = holdfp(fdp, sfd, -1)) == NULL)
2249 * There are two cases of interest here.
2251 * For ENODEV simply dup sfd to file descriptor dfd and return.
2253 * For ENXIO steal away the file structure from sfd and store it
2254 * dfd. sfd is effectively closed by this operation.
2256 * Any other error code is just returned.
2261 * Check that the mode the file is being opened for is a
2262 * subset of the mode of the existing descriptor.
2264 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag)
2266 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2267 fsetfd(p, wfp, dfd);
2272 * Steal away the file pointer from dfd, and stuff it into indx.
2274 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
2275 fsetfd(p, wfp, dfd);
2276 if ((xfp = funsetfd_locked(fdp, sfd)) != NULL)
2278 KKASSERT(xfp == wfp); /* XXX MP RACE */
2289 * NOT MPSAFE - I think these refer to a common file descriptor table
2290 * and we need to spinlock that to link fdtol in.
2292 struct filedesc_to_leader *
2293 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
2294 struct proc *leader)
2296 struct filedesc_to_leader *fdtol;
2298 fdtol = malloc(sizeof(struct filedesc_to_leader),
2299 M_FILEDESC_TO_LEADER, M_WAITOK);
2300 fdtol->fdl_refcount = 1;
2301 fdtol->fdl_holdcount = 0;
2302 fdtol->fdl_wakeup = 0;
2303 fdtol->fdl_leader = leader;
2305 fdtol->fdl_next = old->fdl_next;
2306 fdtol->fdl_prev = old;
2307 old->fdl_next = fdtol;
2308 fdtol->fdl_next->fdl_prev = fdtol;
2310 fdtol->fdl_next = fdtol;
2311 fdtol->fdl_prev = fdtol;
2317 * Scan all file pointers in the system. The callback is made with
2318 * both the master list spinlock held and the fp spinlock held,
2323 * WARNING: both the filehead spinlock and the file pointer spinlock are
2324 * held exclusively when the callback is made. The file pointer is not
2328 allfiles_scan_exclusive(int (*callback)(struct file *, void *), void *data)
2333 spin_lock_wr(&filehead_spin);
2334 LIST_FOREACH(fp, &filehead, f_list) {
2335 spin_lock_wr(&fp->f_spin);
2336 res = callback(fp, data);
2337 spin_unlock_wr(&fp->f_spin);
2341 spin_unlock_wr(&filehead_spin);
2345 * Get file structures.
2347 * NOT MPSAFE - process list scan, SYSCTL_OUT (probably not mpsafe)
2350 struct sysctl_kern_file_info {
2353 struct sysctl_req *req;
2356 static int sysctl_kern_file_callback(struct proc *p, void *data);
2359 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2361 struct sysctl_kern_file_info info;
2364 * Note: because the number of file descriptors is calculated
2365 * in different ways for sizing vs returning the data,
2366 * there is information leakage from the first loop. However,
2367 * it is of a similar order of magnitude to the leakage from
2368 * global system statistics such as kern.openfiles.
2370 * When just doing a count, note that we cannot just count
2371 * the elements and add f_count via the filehead list because
2372 * threaded processes share their descriptor table and f_count might
2373 * still be '1' in that case.
2375 * Since the SYSCTL op can block, we must hold the process to
2376 * prevent it being ripped out from under us either in the
2377 * file descriptor loop or in the greater LIST_FOREACH. The
2378 * process may be in varying states of disrepair. If the process
2379 * is in SZOMB we may have caught it just as it is being removed
2380 * from the allproc list, we must skip it in that case to maintain
2381 * an unbroken chain through the allproc list.
2386 allproc_scan(sysctl_kern_file_callback, &info);
2389 * When just calculating the size, overestimate a bit to try to
2390 * prevent system activity from causing the buffer-fill call
2393 if (req->oldptr == NULL) {
2394 info.count = (info.count + 16) + (info.count / 10);
2395 info.error = SYSCTL_OUT(req, NULL,
2396 info.count * sizeof(struct kinfo_file));
2398 return (info.error);
2402 sysctl_kern_file_callback(struct proc *p, void *data)
2404 struct sysctl_kern_file_info *info = data;
2405 struct kinfo_file kf;
2406 struct filedesc *fdp;
2411 if (p->p_stat == SIDL || (p->p_flag & P_ZOMBIE))
2413 if (!PRISON_CHECK(info->req->td->td_proc->p_ucred, p->p_ucred) != 0)
2415 if ((fdp = p->p_fd) == NULL)
2417 spin_lock_rd(&fdp->fd_spin);
2418 for (n = 0; n < fdp->fd_nfiles; ++n) {
2419 if ((fp = fdp->fd_files[n].fp) == NULL)
2421 if (info->req->oldptr == NULL) {
2424 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
2425 kcore_make_file(&kf, fp, p->p_pid, uid, n);
2426 spin_unlock_rd(&fdp->fd_spin);
2427 info->error = SYSCTL_OUT(info->req, &kf, sizeof(kf));
2428 spin_lock_rd(&fdp->fd_spin);
2433 spin_unlock_rd(&fdp->fd_spin);
2439 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
2440 0, 0, sysctl_kern_file, "S,file", "Entire file table");
2442 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
2443 &maxfilesperproc, 0, "Maximum files allowed open per process");
2445 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
2446 &maxfiles, 0, "Maximum number of files");
2448 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
2449 &maxfilesrootres, 0, "Descriptors reserved for root use");
2451 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
2452 &nfiles, 0, "System-wide number of open files");
2455 fildesc_drvinit(void *unused)
2459 cdevsw_add(&fildesc_cdevsw, 0, 0);
2460 for (fd = 0; fd < NUMFDESC; fd++) {
2461 make_dev(&fildesc_cdevsw, fd,
2462 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
2464 make_dev(&fildesc_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
2465 make_dev(&fildesc_cdevsw, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
2466 make_dev(&fildesc_cdevsw, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
2472 struct fileops badfileops = {
2502 badfo_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *cred)
2511 badfo_poll(struct file *fp, int events, struct ucred *cred)
2520 badfo_kqfilter(struct file *fp, struct knote *kn)
2526 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
2535 badfo_close(struct file *fp)
2544 badfo_shutdown(struct file *fp, int how)
2553 nofo_shutdown(struct file *fp, int how)
2555 return (EOPNOTSUPP);
2558 SYSINIT(fildescdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,
2559 fildesc_drvinit,NULL)