2 * Copyright (c) 2005-2018 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Jeffrey Hsu and Matthew Dillon.
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. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
68 * $FreeBSD: src/sys/kern/kern_descrip.c,v 1.81.2.19 2004/02/28 00:43:31 tegge Exp $
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.h>
74 #include <sys/sysproto.h>
76 #include <sys/device.h>
78 #include <sys/filedesc.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/vnode.h>
83 #include <sys/nlookup.h>
85 #include <sys/filio.h>
86 #include <sys/fcntl.h>
87 #include <sys/unistd.h>
88 #include <sys/resourcevar.h>
89 #include <sys/event.h>
90 #include <sys/kern_syscall.h>
91 #include <sys/kcore.h>
92 #include <sys/kinfo.h>
94 #include <sys/objcache.h>
97 #include <vm/vm_extern.h>
99 #include <sys/file2.h>
100 #include <sys/spinlock2.h>
102 static int fdalloc_locked(struct proc *p, struct filedesc *fdp,
103 int want, int *result);
104 static void fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd);
105 static void fdreserve_locked (struct filedesc *fdp, int fd0, int incr);
106 static struct file *funsetfd_locked (struct filedesc *fdp, int fd);
107 static void ffree(struct file *fp);
109 static MALLOC_DEFINE(M_FILEDESC, "file desc", "Open file descriptor table");
110 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "file desc to leader",
111 "file desc to leader structures");
112 MALLOC_DEFINE(M_FILE, "file", "Open file structure");
113 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
115 static struct krate krate_uidinfo = { .freq = 1 };
117 static d_open_t fdopen;
120 #define CDEV_MAJOR 22
121 static struct dev_ops fildesc_ops = {
127 * Descriptor management.
129 #ifndef NFILELIST_HEADS
130 #define NFILELIST_HEADS 257 /* primary number */
133 struct filelist_head {
134 struct spinlock spin;
135 struct filelist list;
138 static struct filelist_head filelist_heads[NFILELIST_HEADS];
140 static int nfiles; /* actual number of open files */
143 struct lwkt_token revoke_token = LWKT_TOKEN_INITIALIZER(revoke_token);
145 static struct objcache *file_objcache;
147 static struct objcache_malloc_args file_malloc_args = {
148 .objsize = sizeof(struct file),
153 * Fixup fd_freefile and fd_lastfile after a descriptor has been cleared.
155 * must be called with fdp->fd_spin exclusively held
159 fdfixup_locked(struct filedesc *fdp, int fd)
161 if (fd < fdp->fd_freefile) {
162 fdp->fd_freefile = fd;
164 while (fdp->fd_lastfile >= 0 &&
165 fdp->fd_files[fdp->fd_lastfile].fp == NULL &&
166 fdp->fd_files[fdp->fd_lastfile].reserved == 0
173 * Clear the fd thread caches for this fdnode.
175 * If match_fdc is NULL, all thread caches of fdn will be cleared.
176 * The caller must hold fdp->fd_spin exclusively. The threads caching
177 * the descriptor do not have to be the current thread. The (status)
178 * argument is ignored.
180 * If match_fdc is not NULL, only the match_fdc's cache will be cleared.
181 * The caller must hold fdp->fd_spin shared and match_fdc must match a
182 * fdcache entry in curthread. match_fdc has been locked by the caller
183 * and had the specified (status).
185 * Since we are matching against a fp in the fdp (which must still be present
186 * at this time), fp will have at least two refs on any match and we can
187 * decrement the count trivially.
191 fclearcache(struct fdnode *fdn, struct fdcache *match_fdc, int status)
198 * match_fdc == NULL We are cleaning out all tdcache entries
199 * for the fdn and hold fdp->fd_spin exclusively.
200 * This can race against the target threads
201 * cleaning out specific entries.
203 * match_fdc != NULL We are cleaning out a specific tdcache
204 * entry on behalf of the owning thread
205 * and hold fdp->fd_spin shared. The thread
206 * has already locked the entry. This cannot
210 for (i = 0; i < NTDCACHEFD; ++i) {
211 if ((fdc = fdn->tdcache[i]) == NULL)
215 * If match_fdc is non-NULL we are being asked to
216 * clear a specific fdc owned by curthread. There must
217 * be exactly one match. The caller has already locked
218 * the cache entry and will dispose of the lock after
221 * Since we also have a shared lock on fdp, we
222 * can do this without atomic ops.
225 if (fdc != match_fdc)
227 fdn->tdcache[i] = NULL;
228 KASSERT(fp == fdc->fp,
229 ("fclearcache(1): fp mismatch %p/%p\n",
235 * status can be 0 or 2. If 2 the ref is borrowed,
236 * if 0 the ref is not borrowed and we have to drop
240 atomic_add_int(&fp->f_count, -1);
241 fdn->isfull = 0; /* heuristic */
246 * Otherwise we hold an exclusive spin-lock and can only
247 * race thread consumers borrowing cache entries.
249 * Acquire the lock and dispose of the entry. We have to
250 * spin until we get the lock.
253 status = atomic_swap_int(&fdc->locked, 1);
254 if (status == 1) { /* foreign lock, retry */
258 fdn->tdcache[i] = NULL;
259 KASSERT(fp == fdc->fp,
260 ("fclearcache(2): fp mismatch %p/%p\n",
265 atomic_add_int(&fp->f_count, -1);
266 fdn->isfull = 0; /* heuristic */
267 atomic_swap_int(&fdc->locked, 0);
271 KKASSERT(match_fdc == NULL);
275 * Retrieve the fp for the specified fd given the specified file descriptor
276 * table. The fdp does not have to be owned by the current process.
277 * If flags != -1, fp->f_flag must contain at least one of the flags.
279 * This function is not able to cache the fp.
282 holdfp_fdp(struct filedesc *fdp, int fd, int flag)
286 spin_lock_shared(&fdp->fd_spin);
287 if (((u_int)fd) < fdp->fd_nfiles) {
288 fp = fdp->fd_files[fd].fp; /* can be NULL */
290 if ((fp->f_flag & flag) == 0 && flag != -1) {
299 spin_unlock_shared(&fdp->fd_spin);
305 holdfp_fdp_locked(struct filedesc *fdp, int fd, int flag)
309 if (((u_int)fd) < fdp->fd_nfiles) {
310 fp = fdp->fd_files[fd].fp; /* can be NULL */
312 if ((fp->f_flag & flag) == 0 && flag != -1) {
325 * Acquire the fp for the specified file descriptor, using the thread
326 * cache if possible and caching it if possible.
328 * td must be the curren thread.
332 _holdfp_cache(thread_t td, int fd)
334 struct filedesc *fdp;
336 struct fdcache *best;
346 for (fdc = &td->td_fdcache[0]; fdc < &td->td_fdcache[NFDCACHE]; ++fdc) {
347 if (fdc->fd != fd || fdc->fp == NULL)
349 status = atomic_swap_int(&fdc->locked, 1);
352 * If someone else has locked our cache entry they are in
353 * the middle of clearing it, skip the entry.
359 * We have locked the entry, but if it no longer matches
360 * restore the previous state (0 or 2) and skip the entry.
362 if (fdc->fd != fd || fdc->fp == NULL) {
363 atomic_swap_int(&fdc->locked, status);
368 * We have locked a valid entry. We can borrow the ref
369 * for a mode 0 entry. We can get a valid fp for a mode
370 * 2 entry but not borrow the ref.
374 fdc->lru = ++td->td_fdcache_lru;
375 atomic_swap_int(&fdc->locked, 2);
382 fdc->lru = ++td->td_fdcache_lru;
383 atomic_swap_int(&fdc->locked, 2);
391 * Lookup the descriptor the slow way. This can contend against
392 * modifying operations in a multi-threaded environment and cause
393 * cache line ping ponging otherwise.
395 fdp = td->td_proc->p_fd;
396 spin_lock_shared(&fdp->fd_spin);
398 if (((u_int)fd) < fdp->fd_nfiles) {
399 fp = fdp->fd_files[fd].fp; /* can be NULL */
402 if (fdp->fd_files[fd].isfull == 0)
408 spin_unlock_shared(&fdp->fd_spin);
413 * We found a valid fp and held it, fdp is still shared locked.
414 * Enter the fp into the per-thread cache. Find the oldest entry
415 * via lru, or an empty entry.
417 * Because fdp's spinlock is held (shared is fine), no other
418 * thread should be in the middle of clearing our selected entry.
421 best = &td->td_fdcache[0];
422 for (fdc = &td->td_fdcache[0]; fdc < &td->td_fdcache[NFDCACHE]; ++fdc) {
423 if (fdc->fp == NULL) {
427 delta = fdc->lru - best->lru;
435 * Don't enter into the cache if we cannot get the lock.
437 status = atomic_swap_int(&best->locked, 1);
442 * Clear the previous cache entry if present
445 KKASSERT(best->fd >= 0);
446 fclearcache(&fdp->fd_files[best->fd], best, status);
450 * Create our new cache entry. This entry is 'safe' until we tie
451 * into the fdnode. If we cannot tie in, we will clear the entry.
455 best->lru = ++td->td_fdcache_lru;
456 best->locked = 2; /* borrowed ref */
458 fdn = &fdp->fd_files[fd];
459 for (i = 0; i < NTDCACHEFD; ++i) {
460 if (fdn->tdcache[i] == NULL &&
461 atomic_cmpset_ptr((void **)&fdn->tdcache[i], NULL, best)) {
465 fdn->isfull = 1; /* no space */
470 spin_unlock_shared(&fdp->fd_spin);
476 * Drop the file pointer and return to the thread cache if possible.
478 * Caller must not hold fdp's spin lock.
479 * td must be the current thread.
482 dropfp(thread_t td, int fd, struct file *fp)
484 struct filedesc *fdp;
488 fdp = td->td_proc->p_fd;
491 * If our placeholder is still present we can re-cache the ref.
493 * Note that we can race an fclearcache().
495 for (fdc = &td->td_fdcache[0]; fdc < &td->td_fdcache[NFDCACHE]; ++fdc) {
496 if (fdc->fp != fp || fdc->fd != fd)
498 status = atomic_swap_int(&fdc->locked, 1);
502 * Not in mode 2, fdrop fp without caching.
504 atomic_swap_int(&fdc->locked, 0);
508 * Not in mode 2, locked by someone else.
509 * fdrop fp without caching.
514 * Intact borrowed ref, return to mode 0
515 * indicating that we have returned the ref.
517 * Return the borrowed ref (2->1->0)
519 if (fdc->fp == fp && fdc->fd == fd) {
520 atomic_swap_int(&fdc->locked, 0);
523 atomic_swap_int(&fdc->locked, 2);
529 * Failed to re-cache, drop the fp without caching.
535 * Clear all descriptors cached in the per-thread fd cache for
536 * the specified thread.
538 * Caller must not hold p_fd->spin. This function will temporarily
539 * obtain a shared spin lock.
542 fexitcache(thread_t td)
544 struct filedesc *fdp;
549 if (td->td_proc == NULL)
551 fdp = td->td_proc->p_fd;
556 * A shared lock is sufficient as the caller controls td and we
557 * are only clearing td's cache.
559 spin_lock_shared(&fdp->fd_spin);
560 for (i = 0; i < NFDCACHE; ++i) {
561 fdc = &td->td_fdcache[i];
563 status = atomic_swap_int(&fdc->locked, 1);
570 KKASSERT(fdc->fd >= 0);
571 fclearcache(&fdp->fd_files[fdc->fd], fdc,
574 atomic_swap_int(&fdc->locked, 0);
577 spin_unlock_shared(&fdp->fd_spin);
580 static __inline struct filelist_head *
581 fp2filelist(const struct file *fp)
585 i = (u_int)(uintptr_t)fp % NFILELIST_HEADS;
586 return &filelist_heads[i];
591 readplimits(struct proc *p)
593 thread_t td = curthread;
594 struct plimit *limit;
596 limit = td->td_limit;
597 if (limit != p->p_limit) {
598 spin_lock_shared(&p->p_spin);
600 atomic_add_int(&limit->p_refcnt, 1);
601 spin_unlock_shared(&p->p_spin);
603 plimit_free(td->td_limit);
604 td->td_limit = limit;
610 * System calls on descriptors.
613 sys_getdtablesize(struct getdtablesize_args *uap)
615 struct proc *p = curproc;
616 struct plimit *limit = readplimits(p);
619 if (limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
622 dtsize = (int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur;
624 if (dtsize > maxfilesperproc)
625 dtsize = maxfilesperproc;
626 if (dtsize < minfilesperproc)
627 dtsize = minfilesperproc;
628 if (p->p_ucred->cr_uid && dtsize > maxfilesperuser)
629 dtsize = maxfilesperuser;
630 uap->sysmsg_result = dtsize;
635 * Duplicate a file descriptor to a particular value.
637 * note: keep in mind that a potential race condition exists when closing
638 * descriptors from a shared descriptor table (via rfork).
641 sys_dup2(struct dup2_args *uap)
646 error = kern_dup(DUP_FIXED, uap->from, uap->to, &fd);
647 uap->sysmsg_fds[0] = fd;
653 * Duplicate a file descriptor.
656 sys_dup(struct dup_args *uap)
661 error = kern_dup(DUP_VARIABLE, uap->fd, 0, &fd);
662 uap->sysmsg_fds[0] = fd;
668 * MPALMOSTSAFE - acquires mplock for fp operations
671 kern_fcntl(int fd, int cmd, union fcntl_dat *dat, struct ucred *cred)
673 struct thread *td = curthread;
674 struct proc *p = td->td_proc;
681 int tmp, error, flg = F_POSIX;
686 * Operations on file descriptors that do not require a file pointer.
690 error = fgetfdflags(p->p_fd, fd, &tmp);
692 dat->fc_cloexec = (tmp & UF_EXCLOSE) ? FD_CLOEXEC : 0;
696 if (dat->fc_cloexec & FD_CLOEXEC)
697 error = fsetfdflags(p->p_fd, fd, UF_EXCLOSE);
699 error = fclrfdflags(p->p_fd, fd, UF_EXCLOSE);
703 error = kern_dup(DUP_VARIABLE | DUP_FCNTL, fd, newmin,
706 case F_DUPFD_CLOEXEC:
708 error = kern_dup(DUP_VARIABLE | DUP_CLOEXEC | DUP_FCNTL,
709 fd, newmin, &dat->fc_fd);
713 error = kern_dup(DUP_FIXED, fd, newmin, &dat->fc_fd);
715 case F_DUP2FD_CLOEXEC:
717 error = kern_dup(DUP_FIXED | DUP_CLOEXEC, fd, newmin,
725 * Operations on file pointers
727 closedcounter = p->p_fd->fd_closedcounter;
728 if ((fp = holdfp(td, fd, -1)) == NULL)
733 dat->fc_flags = OFLAGS(fp->f_flag);
739 nflags = FFLAGS(dat->fc_flags & ~O_ACCMODE) & FCNTLFLAGS;
740 nflags |= oflags & ~FCNTLFLAGS;
743 if (((nflags ^ oflags) & O_APPEND) && (oflags & FAPPENDONLY))
745 if (error == 0 && ((nflags ^ oflags) & FASYNC)) {
746 tmp = nflags & FASYNC;
747 error = fo_ioctl(fp, FIOASYNC, (caddr_t)&tmp,
752 * If no error, must be atomically set.
757 nflags = (oflags & ~FCNTLFLAGS) | (nflags & FCNTLFLAGS);
758 if (atomic_cmpset_int(&fp->f_flag, oflags, nflags))
765 error = fo_ioctl(fp, FIOGETOWN, (caddr_t)&dat->fc_owner,
770 error = fo_ioctl(fp, FIOSETOWN, (caddr_t)&dat->fc_owner,
776 /* Fall into F_SETLK */
779 if (fp->f_type != DTYPE_VNODE) {
783 vp = (struct vnode *)fp->f_data;
786 * copyin/lockop may block
788 if (dat->fc_flock.l_whence == SEEK_CUR)
789 dat->fc_flock.l_start += fp->f_offset;
791 switch (dat->fc_flock.l_type) {
793 if ((fp->f_flag & FREAD) == 0) {
797 if (p->p_leader->p_advlock_flag == 0)
798 p->p_leader->p_advlock_flag = 1;
799 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
800 &dat->fc_flock, flg);
803 if ((fp->f_flag & FWRITE) == 0) {
807 if (p->p_leader->p_advlock_flag == 0)
808 p->p_leader->p_advlock_flag = 1;
809 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
810 &dat->fc_flock, flg);
813 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
814 &dat->fc_flock, F_POSIX);
822 * It is possible to race a close() on the descriptor while
823 * we were blocked getting the lock. If this occurs the
824 * close might not have caught the lock.
826 if (checkfdclosed(td, p->p_fd, fd, fp, closedcounter)) {
827 dat->fc_flock.l_whence = SEEK_SET;
828 dat->fc_flock.l_start = 0;
829 dat->fc_flock.l_len = 0;
830 dat->fc_flock.l_type = F_UNLCK;
831 VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
832 F_UNLCK, &dat->fc_flock, F_POSIX);
837 if (fp->f_type != DTYPE_VNODE) {
841 vp = (struct vnode *)fp->f_data;
843 * copyin/lockop may block
845 if (dat->fc_flock.l_type != F_RDLCK &&
846 dat->fc_flock.l_type != F_WRLCK &&
847 dat->fc_flock.l_type != F_UNLCK) {
851 if (dat->fc_flock.l_whence == SEEK_CUR)
852 dat->fc_flock.l_start += fp->f_offset;
853 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK,
854 &dat->fc_flock, F_POSIX);
866 * The file control system call.
869 sys_fcntl(struct fcntl_args *uap)
877 case F_DUPFD_CLOEXEC:
878 case F_DUP2FD_CLOEXEC:
879 dat.fc_fd = uap->arg;
882 dat.fc_cloexec = uap->arg;
885 dat.fc_flags = uap->arg;
888 dat.fc_owner = uap->arg;
893 error = copyin((caddr_t)uap->arg, &dat.fc_flock,
894 sizeof(struct flock));
900 error = kern_fcntl(uap->fd, uap->cmd, &dat, curthread->td_ucred);
906 case F_DUPFD_CLOEXEC:
907 case F_DUP2FD_CLOEXEC:
908 uap->sysmsg_result = dat.fc_fd;
911 uap->sysmsg_result = dat.fc_cloexec;
914 uap->sysmsg_result = dat.fc_flags;
917 uap->sysmsg_result = dat.fc_owner;
920 error = copyout(&dat.fc_flock, (caddr_t)uap->arg,
921 sizeof(struct flock));
930 * Common code for dup, dup2, and fcntl(F_DUPFD).
932 * There are four type flags: DUP_FCNTL, DUP_FIXED, DUP_VARIABLE, and
935 * DUP_FCNTL is for handling EINVAL vs. EBADF differences between
936 * fcntl()'s F_DUPFD and F_DUPFD_CLOEXEC and dup2() (per POSIX).
937 * The next two flags are mutually exclusive, and the fourth is optional.
938 * DUP_FIXED tells kern_dup() to destructively dup over an existing file
939 * descriptor if "new" is already open. DUP_VARIABLE tells kern_dup()
940 * to find the lowest unused file descriptor that is greater than or
941 * equal to "new". DUP_CLOEXEC, which works with either of the first
942 * two flags, sets the close-on-exec flag on the "new" file descriptor.
945 kern_dup(int flags, int old, int new, int *res)
947 struct thread *td = curthread;
948 struct proc *p = td->td_proc;
949 struct plimit *limit = readplimits(p);
950 struct filedesc *fdp = p->p_fd;
959 * Verify that we have a valid descriptor to dup from and
960 * possibly to dup to. When the new descriptor is out of
961 * bounds, fcntl()'s F_DUPFD and F_DUPFD_CLOEXEC must
962 * return EINVAL, while dup2() returns EBADF in
965 * NOTE: maxfilesperuser is not applicable to dup()
968 if (limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
971 dtsize = (int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur;
972 if (dtsize > maxfilesperproc)
973 dtsize = maxfilesperproc;
974 if (dtsize < minfilesperproc)
975 dtsize = minfilesperproc;
977 if (new < 0 || new > dtsize)
978 return (flags & DUP_FCNTL ? EINVAL : EBADF);
980 spin_lock(&fdp->fd_spin);
981 if ((unsigned)old >= fdp->fd_nfiles || fdp->fd_files[old].fp == NULL) {
982 spin_unlock(&fdp->fd_spin);
985 if ((flags & DUP_FIXED) && old == new) {
987 if (flags & DUP_CLOEXEC)
988 fdp->fd_files[new].fileflags |= UF_EXCLOSE;
989 spin_unlock(&fdp->fd_spin);
992 fp = fdp->fd_files[old].fp;
993 oldflags = fdp->fd_files[old].fileflags;
997 * Allocate a new descriptor if DUP_VARIABLE, or expand the table
998 * if the requested descriptor is beyond the current table size.
1000 * This can block. Retry if the source descriptor no longer matches
1001 * or if our expectation in the expansion case races.
1003 * If we are not expanding or allocating a new decriptor, then reset
1004 * the target descriptor to a reserved state so we have a uniform
1005 * setup for the next code block.
1007 if ((flags & DUP_VARIABLE) || new >= fdp->fd_nfiles) {
1008 error = fdalloc_locked(p, fdp, new, &newfd);
1010 spin_unlock(&fdp->fd_spin);
1017 if (old >= fdp->fd_nfiles || fdp->fd_files[old].fp != fp) {
1018 fsetfd_locked(fdp, NULL, newfd);
1019 spin_unlock(&fdp->fd_spin);
1024 * Check for expansion race
1026 if ((flags & DUP_VARIABLE) == 0 && new != newfd) {
1027 fsetfd_locked(fdp, NULL, newfd);
1028 spin_unlock(&fdp->fd_spin);
1033 * Check for ripout, newfd reused old (this case probably
1037 fsetfd_locked(fdp, NULL, newfd);
1038 spin_unlock(&fdp->fd_spin);
1045 if (fdp->fd_files[new].reserved) {
1046 spin_unlock(&fdp->fd_spin);
1048 kprintf("Warning: dup(): target descriptor %d is "
1049 "reserved, waiting for it to be resolved\n",
1051 tsleep(fdp, 0, "fdres", hz);
1056 * If the target descriptor was never allocated we have
1057 * to allocate it. If it was we have to clean out the
1058 * old descriptor. delfp inherits the ref from the
1061 ++fdp->fd_closedcounter;
1062 fclearcache(&fdp->fd_files[new], NULL, 0);
1063 ++fdp->fd_closedcounter;
1064 delfp = fdp->fd_files[new].fp;
1065 fdp->fd_files[new].fp = NULL;
1066 fdp->fd_files[new].reserved = 1;
1067 if (delfp == NULL) {
1068 fdreserve_locked(fdp, new, 1);
1069 if (new > fdp->fd_lastfile)
1070 fdp->fd_lastfile = new;
1076 * NOTE: still holding an exclusive spinlock
1080 * If a descriptor is being overwritten we may hve to tell
1081 * fdfree() to sleep to ensure that all relevant process
1082 * leaders can be traversed in closef().
1084 if (delfp != NULL && p->p_fdtol != NULL) {
1085 fdp->fd_holdleaderscount++;
1090 KASSERT(delfp == NULL || (flags & DUP_FIXED),
1091 ("dup() picked an open file"));
1094 * Duplicate the source descriptor, update lastfile. If the new
1095 * descriptor was not allocated and we aren't replacing an existing
1096 * descriptor we have to mark the descriptor as being in use.
1098 * The fd_files[] array inherits fp's hold reference.
1100 fsetfd_locked(fdp, fp, new);
1101 if ((flags & DUP_CLOEXEC) != 0)
1102 fdp->fd_files[new].fileflags = oldflags | UF_EXCLOSE;
1104 fdp->fd_files[new].fileflags = oldflags & ~UF_EXCLOSE;
1105 spin_unlock(&fdp->fd_spin);
1110 * If we dup'd over a valid file, we now own the reference to it
1111 * and must dispose of it using closef() semantics (as if a
1112 * close() were performed on it).
1115 if (SLIST_FIRST(&delfp->f_klist))
1116 knote_fdclose(delfp, fdp, new);
1119 spin_lock(&fdp->fd_spin);
1120 fdp->fd_holdleaderscount--;
1121 if (fdp->fd_holdleaderscount == 0 &&
1122 fdp->fd_holdleaderswakeup != 0) {
1123 fdp->fd_holdleaderswakeup = 0;
1124 spin_unlock(&fdp->fd_spin);
1125 wakeup(&fdp->fd_holdleaderscount);
1127 spin_unlock(&fdp->fd_spin);
1135 * If sigio is on the list associated with a process or process group,
1136 * disable signalling from the device, remove sigio from the list and
1140 funsetown(struct sigio **sigiop)
1144 struct sigio *sigio;
1146 if ((sigio = *sigiop) != NULL) {
1147 lwkt_gettoken(&sigio_token); /* protect sigio */
1148 KKASSERT(sigiop == sigio->sio_myref);
1151 lwkt_reltoken(&sigio_token);
1156 if (sigio->sio_pgid < 0) {
1157 pgrp = sigio->sio_pgrp;
1158 sigio->sio_pgrp = NULL;
1159 lwkt_gettoken(&pgrp->pg_token);
1160 SLIST_REMOVE(&pgrp->pg_sigiolst, sigio, sigio, sio_pgsigio);
1161 lwkt_reltoken(&pgrp->pg_token);
1163 } else /* if ((*sigiop)->sio_pgid > 0) */ {
1164 p = sigio->sio_proc;
1165 sigio->sio_proc = NULL;
1167 lwkt_gettoken(&p->p_token);
1168 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1169 lwkt_reltoken(&p->p_token);
1172 crfree(sigio->sio_ucred);
1173 sigio->sio_ucred = NULL;
1174 kfree(sigio, M_SIGIO);
1178 * Free a list of sigio structures. Caller is responsible for ensuring
1179 * that the list is MPSAFE.
1182 funsetownlst(struct sigiolst *sigiolst)
1184 struct sigio *sigio;
1186 while ((sigio = SLIST_FIRST(sigiolst)) != NULL)
1187 funsetown(sigio->sio_myref);
1191 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1193 * After permission checking, add a sigio structure to the sigio list for
1194 * the process or process group.
1197 fsetown(pid_t pgid, struct sigio **sigiop)
1199 struct proc *proc = NULL;
1200 struct pgrp *pgrp = NULL;
1201 struct sigio *sigio;
1217 * Policy - Don't allow a process to FSETOWN a process
1218 * in another session.
1220 * Remove this test to allow maximum flexibility or
1221 * restrict FSETOWN to the current process or process
1222 * group for maximum safety.
1224 if (proc->p_session != curproc->p_session) {
1228 } else /* if (pgid < 0) */ {
1229 pgrp = pgfind(-pgid);
1236 * Policy - Don't allow a process to FSETOWN a process
1237 * in another session.
1239 * Remove this test to allow maximum flexibility or
1240 * restrict FSETOWN to the current process or process
1241 * group for maximum safety.
1243 if (pgrp->pg_session != curproc->p_session) {
1248 sigio = kmalloc(sizeof(struct sigio), M_SIGIO, M_WAITOK | M_ZERO);
1250 KKASSERT(pgrp == NULL);
1251 lwkt_gettoken(&proc->p_token);
1252 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1253 sigio->sio_proc = proc;
1254 lwkt_reltoken(&proc->p_token);
1256 KKASSERT(proc == NULL);
1257 lwkt_gettoken(&pgrp->pg_token);
1258 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1259 sigio->sio_pgrp = pgrp;
1260 lwkt_reltoken(&pgrp->pg_token);
1263 sigio->sio_pgid = pgid;
1264 sigio->sio_ucred = crhold(curthread->td_ucred);
1265 /* It would be convenient if p_ruid was in ucred. */
1266 sigio->sio_ruid = sigio->sio_ucred->cr_ruid;
1267 sigio->sio_myref = sigiop;
1269 lwkt_gettoken(&sigio_token);
1273 lwkt_reltoken(&sigio_token);
1284 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1287 fgetown(struct sigio **sigiop)
1289 struct sigio *sigio;
1292 lwkt_gettoken_shared(&sigio_token);
1294 own = (sigio != NULL ? sigio->sio_pgid : 0);
1295 lwkt_reltoken(&sigio_token);
1301 * Close many file descriptors.
1304 sys_closefrom(struct closefrom_args *uap)
1306 return(kern_closefrom(uap->fd));
1310 * Close all file descriptors greater then or equal to fd
1313 kern_closefrom(int fd)
1315 struct thread *td = curthread;
1316 struct proc *p = td->td_proc;
1317 struct filedesc *fdp;
1328 * NOTE: This function will skip unassociated descriptors and
1329 * reserved descriptors that have not yet been assigned.
1330 * fd_lastfile can change as a side effect of kern_close().
1332 * NOTE: We accumulate EINTR errors and return EINTR if any
1333 * close() returned EINTR. However, the descriptor is
1334 * still closed and we do not break out of the loop.
1337 spin_lock(&fdp->fd_spin);
1338 while (fd <= fdp->fd_lastfile) {
1339 if (fdp->fd_files[fd].fp != NULL) {
1340 spin_unlock(&fdp->fd_spin);
1341 /* ok if this races another close */
1342 e2 = kern_close(fd);
1345 spin_lock(&fdp->fd_spin);
1349 spin_unlock(&fdp->fd_spin);
1355 * Close a file descriptor.
1358 sys_close(struct close_args *uap)
1360 return(kern_close(uap->fd));
1369 struct thread *td = curthread;
1370 struct proc *p = td->td_proc;
1371 struct filedesc *fdp;
1380 * funsetfd*() also clears the fd cache
1382 spin_lock(&fdp->fd_spin);
1383 if ((fp = funsetfd_locked(fdp, fd)) == NULL) {
1384 spin_unlock(&fdp->fd_spin);
1388 if (p->p_fdtol != NULL) {
1390 * Ask fdfree() to sleep to ensure that all relevant
1391 * process leaders can be traversed in closef().
1393 fdp->fd_holdleaderscount++;
1398 * we now hold the fp reference that used to be owned by the descriptor
1401 spin_unlock(&fdp->fd_spin);
1402 if (SLIST_FIRST(&fp->f_klist))
1403 knote_fdclose(fp, fdp, fd);
1404 error = closef(fp, p);
1406 spin_lock(&fdp->fd_spin);
1407 fdp->fd_holdleaderscount--;
1408 if (fdp->fd_holdleaderscount == 0 &&
1409 fdp->fd_holdleaderswakeup != 0) {
1410 fdp->fd_holdleaderswakeup = 0;
1411 spin_unlock(&fdp->fd_spin);
1412 wakeup(&fdp->fd_holdleaderscount);
1414 spin_unlock(&fdp->fd_spin);
1421 * shutdown_args(int fd, int how)
1424 kern_shutdown(int fd, int how)
1426 struct thread *td = curthread;
1430 if ((fp = holdfp(td, fd, -1)) == NULL)
1432 error = fo_shutdown(fp, how);
1442 sys_shutdown(struct shutdown_args *uap)
1446 error = kern_shutdown(uap->s, uap->how);
1455 kern_fstat(int fd, struct stat *ub)
1457 struct thread *td = curthread;
1461 if ((fp = holdfp(td, fd, -1)) == NULL)
1463 error = fo_stat(fp, ub, td->td_ucred);
1470 * Return status information about a file descriptor.
1473 sys_fstat(struct fstat_args *uap)
1478 error = kern_fstat(uap->fd, &st);
1481 error = copyout(&st, uap->sb, sizeof(st));
1486 * Return pathconf information about a file descriptor.
1491 sys_fpathconf(struct fpathconf_args *uap)
1493 struct thread *td = curthread;
1498 if ((fp = holdfp(td, uap->fd, -1)) == NULL)
1501 switch (fp->f_type) {
1504 if (uap->name != _PC_PIPE_BUF) {
1507 uap->sysmsg_result = PIPE_BUF;
1513 vp = (struct vnode *)fp->f_data;
1514 error = VOP_PATHCONF(vp, uap->name, &uap->sysmsg_reg);
1525 * Grow the file table so it can hold through descriptor (want).
1527 * The fdp's spinlock must be held exclusively on entry and may be held
1528 * exclusively on return. The spinlock may be cycled by the routine.
1531 fdgrow_locked(struct filedesc *fdp, int want)
1533 struct fdnode *newfiles;
1534 struct fdnode *oldfiles;
1537 nf = fdp->fd_nfiles;
1539 /* nf has to be of the form 2^n - 1 */
1541 } while (nf <= want);
1543 spin_unlock(&fdp->fd_spin);
1544 newfiles = kmalloc(nf * sizeof(struct fdnode), M_FILEDESC, M_WAITOK);
1545 spin_lock(&fdp->fd_spin);
1548 * We could have raced another extend while we were not holding
1551 if (fdp->fd_nfiles >= nf) {
1552 spin_unlock(&fdp->fd_spin);
1553 kfree(newfiles, M_FILEDESC);
1554 spin_lock(&fdp->fd_spin);
1558 * Copy the existing ofile and ofileflags arrays
1559 * and zero the new portion of each array.
1561 extra = nf - fdp->fd_nfiles;
1562 bcopy(fdp->fd_files, newfiles, fdp->fd_nfiles * sizeof(struct fdnode));
1563 bzero(&newfiles[fdp->fd_nfiles], extra * sizeof(struct fdnode));
1565 oldfiles = fdp->fd_files;
1566 fdp->fd_files = newfiles;
1567 fdp->fd_nfiles = nf;
1569 if (oldfiles != fdp->fd_builtin_files) {
1570 spin_unlock(&fdp->fd_spin);
1571 kfree(oldfiles, M_FILEDESC);
1572 spin_lock(&fdp->fd_spin);
1577 * Number of nodes in right subtree, including the root.
1580 right_subtree_size(int n)
1582 return (n ^ (n | (n + 1)));
1589 right_ancestor(int n)
1591 return (n | (n + 1));
1598 left_ancestor(int n)
1600 return ((n & (n + 1)) - 1);
1604 * Traverse the in-place binary tree buttom-up adjusting the allocation
1605 * count so scans can determine where free descriptors are located.
1607 * caller must be holding an exclusive spinlock on fdp
1611 fdreserve_locked(struct filedesc *fdp, int fd, int incr)
1614 fdp->fd_files[fd].allocated += incr;
1615 KKASSERT(fdp->fd_files[fd].allocated >= 0);
1616 fd = left_ancestor(fd);
1621 * Reserve a file descriptor for the process. If no error occurs, the
1622 * caller MUST at some point call fsetfd() or assign a file pointer
1623 * or dispose of the reservation.
1627 fdalloc_locked(struct proc *p, struct filedesc *fdp, int want, int *result)
1629 struct plimit *limit = readplimits(p);
1630 struct uidinfo *uip;
1631 int fd, rsize, rsum, node, lim;
1634 * Check dtable size limit
1636 *result = -1; /* avoid gcc warnings */
1637 if (limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
1640 lim = (int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur;
1642 if (lim > maxfilesperproc)
1643 lim = maxfilesperproc;
1644 if (lim < minfilesperproc)
1645 lim = minfilesperproc;
1650 * Check that the user has not run out of descriptors (non-root only).
1651 * As a safety measure the dtable is allowed to have at least
1652 * minfilesperproc open fds regardless of the maxfilesperuser limit.
1654 * This isn't as loose a spec as ui_posixlocks, so we use atomic
1655 * ops to force synchronize and recheck if we would otherwise
1658 if (p->p_ucred->cr_uid && fdp->fd_nfiles >= minfilesperproc) {
1659 uip = p->p_ucred->cr_uidinfo;
1660 if (uip->ui_openfiles > maxfilesperuser) {
1665 for (n = 0; n < ncpus; ++n) {
1666 count += atomic_swap_int(
1667 &uip->ui_pcpu[n].pu_openfiles, 0);
1669 atomic_add_int(&uip->ui_openfiles, count);
1670 if (uip->ui_openfiles > maxfilesperuser) {
1671 krateprintf(&krate_uidinfo,
1672 "Warning: user %d pid %d (%s) "
1673 "ran out of file descriptors "
1675 p->p_ucred->cr_uid, (int)p->p_pid,
1677 uip->ui_openfiles, maxfilesperuser);
1684 * Grow the dtable if necessary
1686 if (want >= fdp->fd_nfiles)
1687 fdgrow_locked(fdp, want);
1690 * Search for a free descriptor starting at the higher
1691 * of want or fd_freefile. If that fails, consider
1692 * expanding the ofile array.
1694 * NOTE! the 'allocated' field is a cumulative recursive allocation
1695 * count. If we happen to see a value of 0 then we can shortcut
1696 * our search. Otherwise we run through through the tree going
1697 * down branches we know have free descriptor(s) until we hit a
1698 * leaf node. The leaf node will be free but will not necessarily
1699 * have an allocated field of 0.
1702 /* move up the tree looking for a subtree with a free node */
1703 for (fd = max(want, fdp->fd_freefile); fd < min(fdp->fd_nfiles, lim);
1704 fd = right_ancestor(fd)) {
1705 if (fdp->fd_files[fd].allocated == 0)
1708 rsize = right_subtree_size(fd);
1709 if (fdp->fd_files[fd].allocated == rsize)
1710 continue; /* right subtree full */
1713 * Free fd is in the right subtree of the tree rooted at fd.
1714 * Call that subtree R. Look for the smallest (leftmost)
1715 * subtree of R with an unallocated fd: continue moving
1716 * down the left branch until encountering a full left
1717 * subtree, then move to the right.
1719 for (rsum = 0, rsize /= 2; rsize > 0; rsize /= 2) {
1721 rsum += fdp->fd_files[node].allocated;
1722 if (fdp->fd_files[fd].allocated == rsum + rsize) {
1723 fd = node; /* move to the right */
1724 if (fdp->fd_files[node].allocated == 0)
1733 * No space in current array. Expand?
1735 if (fdp->fd_nfiles >= lim) {
1738 fdgrow_locked(fdp, want);
1742 KKASSERT(fd < fdp->fd_nfiles);
1743 if (fd > fdp->fd_lastfile)
1744 fdp->fd_lastfile = fd;
1745 if (want <= fdp->fd_freefile)
1746 fdp->fd_freefile = fd;
1748 KKASSERT(fdp->fd_files[fd].fp == NULL);
1749 KKASSERT(fdp->fd_files[fd].reserved == 0);
1750 fdp->fd_files[fd].fileflags = 0;
1751 fdp->fd_files[fd].reserved = 1;
1752 fdreserve_locked(fdp, fd, 1);
1758 fdalloc(struct proc *p, int want, int *result)
1760 struct filedesc *fdp = p->p_fd;
1763 spin_lock(&fdp->fd_spin);
1764 error = fdalloc_locked(p, fdp, want, result);
1765 spin_unlock(&fdp->fd_spin);
1771 * Check to see whether n user file descriptors
1772 * are available to the process p.
1775 fdavail(struct proc *p, int n)
1777 struct plimit *limit = readplimits(p);
1778 struct filedesc *fdp = p->p_fd;
1779 struct fdnode *fdnode;
1782 if (limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur > INT_MAX)
1785 lim = (int)limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur;
1787 if (lim > maxfilesperproc)
1788 lim = maxfilesperproc;
1789 if (lim < minfilesperproc)
1790 lim = minfilesperproc;
1792 spin_lock(&fdp->fd_spin);
1793 if ((i = lim - fdp->fd_nfiles) > 0 && (n -= i) <= 0) {
1794 spin_unlock(&fdp->fd_spin);
1797 last = min(fdp->fd_nfiles, lim);
1798 fdnode = &fdp->fd_files[fdp->fd_freefile];
1799 for (i = last - fdp->fd_freefile; --i >= 0; ++fdnode) {
1800 if (fdnode->fp == NULL && --n <= 0) {
1801 spin_unlock(&fdp->fd_spin);
1805 spin_unlock(&fdp->fd_spin);
1810 * Revoke open descriptors referencing (f_data, f_type)
1812 * Any revoke executed within a prison is only able to
1813 * revoke descriptors for processes within that prison.
1815 * Returns 0 on success or an error code.
1817 struct fdrevoke_info {
1826 static int fdrevoke_check_callback(struct file *fp, void *vinfo);
1827 static int fdrevoke_proc_callback(struct proc *p, void *vinfo);
1830 fdrevoke(void *f_data, short f_type, struct ucred *cred)
1832 struct fdrevoke_info info;
1835 bzero(&info, sizeof(info));
1839 error = falloc(NULL, &info.nfp, NULL);
1844 * Scan the file pointer table once. dups do not dup file pointers,
1845 * only descriptors, so there is no leak. Set FREVOKED on the fps
1848 * Any fps sent over unix-domain sockets will be revoked by the
1849 * socket code checking for FREVOKED when the fps are externialized.
1850 * revoke_token is used to make sure that fps marked FREVOKED and
1851 * externalized will be picked up by the following allproc_scan().
1853 lwkt_gettoken(&revoke_token);
1854 allfiles_scan_exclusive(fdrevoke_check_callback, &info);
1855 lwkt_reltoken(&revoke_token);
1858 * If any fps were marked track down the related descriptors
1859 * and close them. Any dup()s at this point will notice
1860 * the FREVOKED already set in the fp and do the right thing.
1863 allproc_scan(fdrevoke_proc_callback, &info, 0);
1869 * Locate matching file pointers directly.
1871 * WARNING: allfiles_scan_exclusive() holds a spinlock through these calls!
1874 fdrevoke_check_callback(struct file *fp, void *vinfo)
1876 struct fdrevoke_info *info = vinfo;
1879 * File pointers already flagged for revokation are skipped.
1881 if (fp->f_flag & FREVOKED)
1885 * If revoking from a prison file pointers created outside of
1886 * that prison, or file pointers without creds, cannot be revoked.
1888 if (info->cred->cr_prison &&
1889 (fp->f_cred == NULL ||
1890 info->cred->cr_prison != fp->f_cred->cr_prison)) {
1895 * If the file pointer matches then mark it for revocation. The
1896 * flag is currently only used by unp_revoke_gc().
1898 * info->found is a heuristic and can race in a SMP environment.
1900 if (info->data == fp->f_data && info->type == fp->f_type) {
1901 atomic_set_int(&fp->f_flag, FREVOKED);
1908 * Locate matching file pointers via process descriptor tables.
1911 fdrevoke_proc_callback(struct proc *p, void *vinfo)
1913 struct fdrevoke_info *info = vinfo;
1914 struct filedesc *fdp;
1918 if (p->p_stat == SIDL || p->p_stat == SZOMB)
1920 if (info->cred->cr_prison &&
1921 info->cred->cr_prison != p->p_ucred->cr_prison) {
1926 * If the controlling terminal of the process matches the
1927 * vnode being revoked we clear the controlling terminal.
1929 * The normal spec_close() may not catch this because it
1930 * uses curproc instead of p.
1932 if (p->p_session && info->type == DTYPE_VNODE &&
1933 info->data == p->p_session->s_ttyvp) {
1934 p->p_session->s_ttyvp = NULL;
1939 * Softref the fdp to prevent it from being destroyed
1941 spin_lock(&p->p_spin);
1942 if ((fdp = p->p_fd) == NULL) {
1943 spin_unlock(&p->p_spin);
1946 atomic_add_int(&fdp->fd_softrefs, 1);
1947 spin_unlock(&p->p_spin);
1950 * Locate and close any matching file descriptors, replacing
1951 * them with info->nfp.
1953 spin_lock(&fdp->fd_spin);
1954 for (n = 0; n < fdp->fd_nfiles; ++n) {
1955 if ((fp = fdp->fd_files[n].fp) == NULL)
1957 if (fp->f_flag & FREVOKED) {
1958 ++fdp->fd_closedcounter;
1959 fclearcache(&fdp->fd_files[n], NULL, 0);
1960 ++fdp->fd_closedcounter;
1962 fdp->fd_files[n].fp = info->nfp;
1963 spin_unlock(&fdp->fd_spin);
1964 knote_fdclose(fp, fdp, n); /* XXX */
1966 spin_lock(&fdp->fd_spin);
1969 spin_unlock(&fdp->fd_spin);
1970 atomic_subtract_int(&fdp->fd_softrefs, 1);
1976 * Create a new open file structure and reserve a file decriptor
1977 * for the process that refers to it.
1979 * Root creds are checked using lp, or assumed if lp is NULL. If
1980 * resultfd is non-NULL then lp must also be non-NULL. No file
1981 * descriptor is reserved (and no process context is needed) if
1984 * A file pointer with a refcount of 1 is returned. Note that the
1985 * file pointer is NOT associated with the descriptor. If falloc
1986 * returns success, fsetfd() MUST be called to either associate the
1987 * file pointer or clear the reservation.
1990 falloc(struct lwp *lp, struct file **resultfp, int *resultfd)
1992 static struct timeval lastfail;
1994 struct filelist_head *head;
1996 struct ucred *cred = lp ? lp->lwp_thread->td_ucred : proc0.p_ucred;
2002 * Handle filetable full issues and root overfill.
2004 if (nfiles >= maxfiles - maxfilesrootres &&
2005 (cred->cr_ruid != 0 || nfiles >= maxfiles)) {
2006 if (ppsratecheck(&lastfail, &curfail, 1)) {
2007 kprintf("kern.maxfiles limit exceeded by uid %d, "
2008 "please see tuning(7).\n",
2016 * Allocate a new file descriptor.
2018 fp = objcache_get(file_objcache, M_WAITOK);
2019 bzero(fp, sizeof(*fp));
2020 spin_init(&fp->f_spin, "falloc");
2021 SLIST_INIT(&fp->f_klist);
2023 fp->f_ops = &badfileops;
2026 atomic_add_int(&nfiles, 1);
2028 head = fp2filelist(fp);
2029 spin_lock(&head->spin);
2030 LIST_INSERT_HEAD(&head->list, fp, f_list);
2031 spin_unlock(&head->spin);
2034 if ((error = fdalloc(lp->lwp_proc, 0, resultfd)) != 0) {
2047 * Check for races against a file descriptor by determining that the
2048 * file pointer is still associated with the specified file descriptor,
2049 * and a close is not currently in progress.
2052 checkfdclosed(thread_t td, struct filedesc *fdp, int fd, struct file *fp,
2055 struct fdcache *fdc;
2059 if (fdp->fd_closedcounter == closedcounter)
2062 if (td->td_proc && td->td_proc->p_fd == fdp) {
2063 for (fdc = &td->td_fdcache[0];
2064 fdc < &td->td_fdcache[NFDCACHE]; ++fdc) {
2065 if (fdc->fd == fd && fdc->fp == fp)
2070 spin_lock_shared(&fdp->fd_spin);
2071 if ((unsigned)fd >= fdp->fd_nfiles || fp != fdp->fd_files[fd].fp)
2075 spin_unlock_shared(&fdp->fd_spin);
2080 * Associate a file pointer with a previously reserved file descriptor.
2081 * This function always succeeds.
2083 * If fp is NULL, the file descriptor is returned to the pool.
2085 * Caller must hold an exclusive spinlock on fdp->fd_spin.
2088 fsetfd_locked(struct filedesc *fdp, struct file *fp, int fd)
2090 KKASSERT((unsigned)fd < fdp->fd_nfiles);
2091 KKASSERT(fdp->fd_files[fd].reserved != 0);
2094 /* fclearcache(&fdp->fd_files[fd], NULL, 0); */
2095 fdp->fd_files[fd].fp = fp;
2096 fdp->fd_files[fd].reserved = 0;
2098 fdp->fd_files[fd].reserved = 0;
2099 fdreserve_locked(fdp, fd, -1);
2100 fdfixup_locked(fdp, fd);
2105 * Caller must hold an exclusive spinlock on fdp->fd_spin.
2108 fsetfd(struct filedesc *fdp, struct file *fp, int fd)
2110 spin_lock(&fdp->fd_spin);
2111 fsetfd_locked(fdp, fp, fd);
2112 spin_unlock(&fdp->fd_spin);
2116 * Caller must hold an exclusive spinlock on fdp->fd_spin.
2120 funsetfd_locked(struct filedesc *fdp, int fd)
2124 if ((unsigned)fd >= fdp->fd_nfiles)
2126 if ((fp = fdp->fd_files[fd].fp) == NULL)
2128 ++fdp->fd_closedcounter;
2129 fclearcache(&fdp->fd_files[fd], NULL, 0);
2130 fdp->fd_files[fd].fp = NULL;
2131 fdp->fd_files[fd].fileflags = 0;
2132 ++fdp->fd_closedcounter;
2134 fdreserve_locked(fdp, fd, -1);
2135 fdfixup_locked(fdp, fd);
2141 * WARNING: May not be called before initial fsetfd().
2144 fgetfdflags(struct filedesc *fdp, int fd, int *flagsp)
2148 spin_lock_shared(&fdp->fd_spin);
2149 if (((u_int)fd) >= fdp->fd_nfiles) {
2151 } else if (fdp->fd_files[fd].fp == NULL) {
2154 *flagsp = fdp->fd_files[fd].fileflags;
2157 spin_unlock_shared(&fdp->fd_spin);
2163 * WARNING: May not be called before initial fsetfd().
2166 fsetfdflags(struct filedesc *fdp, int fd, int add_flags)
2170 spin_lock(&fdp->fd_spin);
2171 if (((u_int)fd) >= fdp->fd_nfiles) {
2173 } else if (fdp->fd_files[fd].fp == NULL) {
2176 fdp->fd_files[fd].fileflags |= add_flags;
2179 spin_unlock(&fdp->fd_spin);
2185 * WARNING: May not be called before initial fsetfd().
2188 fclrfdflags(struct filedesc *fdp, int fd, int rem_flags)
2192 spin_lock(&fdp->fd_spin);
2193 if (((u_int)fd) >= fdp->fd_nfiles) {
2195 } else if (fdp->fd_files[fd].fp == NULL) {
2198 fdp->fd_files[fd].fileflags &= ~rem_flags;
2201 spin_unlock(&fdp->fd_spin);
2207 * Set/Change/Clear the creds for a fp and synchronize the uidinfo.
2210 fsetcred(struct file *fp, struct ucred *ncr)
2213 struct uidinfo *uip;
2214 struct uidcount *pup;
2219 if (ocr == NULL || ncr == NULL || ocr->cr_uidinfo != ncr->cr_uidinfo) {
2221 uip = ocr->cr_uidinfo;
2222 pup = &uip->ui_pcpu[cpu];
2223 atomic_add_int(&pup->pu_openfiles, -1);
2224 if (pup->pu_openfiles < -PUP_LIMIT ||
2225 pup->pu_openfiles > PUP_LIMIT) {
2226 count = atomic_swap_int(&pup->pu_openfiles, 0);
2227 atomic_add_int(&uip->ui_openfiles, count);
2231 uip = ncr->cr_uidinfo;
2232 pup = &uip->ui_pcpu[cpu];
2233 atomic_add_int(&pup->pu_openfiles, 1);
2234 if (pup->pu_openfiles < -PUP_LIMIT ||
2235 pup->pu_openfiles > PUP_LIMIT) {
2236 count = atomic_swap_int(&pup->pu_openfiles, 0);
2237 atomic_add_int(&uip->ui_openfiles, count);
2249 * Free a file descriptor.
2253 ffree(struct file *fp)
2255 KASSERT((fp->f_count == 0), ("ffree: fp_fcount not 0!"));
2257 if (fp->f_nchandle.ncp)
2258 cache_drop(&fp->f_nchandle);
2259 objcache_put(file_objcache, fp);
2263 * called from init_main, initialize filedesc0 for proc0.
2266 fdinit_bootstrap(struct proc *p0, struct filedesc *fdp0, int cmask)
2270 fdp0->fd_refcnt = 1;
2271 fdp0->fd_cmask = cmask;
2272 fdp0->fd_files = fdp0->fd_builtin_files;
2273 fdp0->fd_nfiles = NDFILE;
2274 fdp0->fd_lastfile = -1;
2275 spin_init(&fdp0->fd_spin, "fdinitbootstrap");
2279 * Build a new filedesc structure.
2282 fdinit(struct proc *p)
2284 struct filedesc *newfdp;
2285 struct filedesc *fdp = p->p_fd;
2287 newfdp = kmalloc(sizeof(struct filedesc), M_FILEDESC, M_WAITOK|M_ZERO);
2288 spin_lock(&fdp->fd_spin);
2290 newfdp->fd_cdir = fdp->fd_cdir;
2291 vref(newfdp->fd_cdir);
2292 cache_copy(&fdp->fd_ncdir, &newfdp->fd_ncdir);
2296 * rdir may not be set in e.g. proc0 or anything vm_fork'd off of
2297 * proc0, but should unconditionally exist in other processes.
2300 newfdp->fd_rdir = fdp->fd_rdir;
2301 vref(newfdp->fd_rdir);
2302 cache_copy(&fdp->fd_nrdir, &newfdp->fd_nrdir);
2305 newfdp->fd_jdir = fdp->fd_jdir;
2306 vref(newfdp->fd_jdir);
2307 cache_copy(&fdp->fd_njdir, &newfdp->fd_njdir);
2309 spin_unlock(&fdp->fd_spin);
2311 /* Create the file descriptor table. */
2312 newfdp->fd_refcnt = 1;
2313 newfdp->fd_cmask = cmask;
2314 newfdp->fd_files = newfdp->fd_builtin_files;
2315 newfdp->fd_nfiles = NDFILE;
2316 newfdp->fd_lastfile = -1;
2317 spin_init(&newfdp->fd_spin, "fdinit");
2323 * Share a filedesc structure.
2326 fdshare(struct proc *p)
2328 struct filedesc *fdp;
2331 spin_lock(&fdp->fd_spin);
2333 spin_unlock(&fdp->fd_spin);
2338 * Copy a filedesc structure.
2341 fdcopy(struct proc *p, struct filedesc **fpp)
2343 struct filedesc *fdp = p->p_fd;
2344 struct filedesc *newfdp;
2345 struct fdnode *fdnode;
2350 * Certain daemons might not have file descriptors.
2356 * Allocate the new filedesc and fd_files[] array. This can race
2357 * with operations by other threads on the fdp so we have to be
2360 newfdp = kmalloc(sizeof(struct filedesc),
2361 M_FILEDESC, M_WAITOK | M_ZERO | M_NULLOK);
2362 if (newfdp == NULL) {
2367 spin_lock(&fdp->fd_spin);
2368 if (fdp->fd_lastfile < NDFILE) {
2369 newfdp->fd_files = newfdp->fd_builtin_files;
2373 * We have to allocate (N^2-1) entries for our in-place
2374 * binary tree. Allow the table to shrink.
2378 while (ni > fdp->fd_lastfile && ni > NDFILE) {
2382 spin_unlock(&fdp->fd_spin);
2383 newfdp->fd_files = kmalloc(i * sizeof(struct fdnode),
2384 M_FILEDESC, M_WAITOK | M_ZERO);
2387 * Check for race, retry
2389 spin_lock(&fdp->fd_spin);
2390 if (i <= fdp->fd_lastfile) {
2391 spin_unlock(&fdp->fd_spin);
2392 kfree(newfdp->fd_files, M_FILEDESC);
2398 * Dup the remaining fields. vref() and cache_hold() can be
2399 * safely called while holding the read spinlock on fdp.
2401 * The read spinlock on fdp is still being held.
2403 * NOTE: vref and cache_hold calls for the case where the vnode
2404 * or cache entry already has at least one ref may be called
2405 * while holding spin locks.
2407 if ((newfdp->fd_cdir = fdp->fd_cdir) != NULL) {
2408 vref(newfdp->fd_cdir);
2409 cache_copy(&fdp->fd_ncdir, &newfdp->fd_ncdir);
2412 * We must check for fd_rdir here, at least for now because
2413 * the init process is created before we have access to the
2414 * rootvode to take a reference to it.
2416 if ((newfdp->fd_rdir = fdp->fd_rdir) != NULL) {
2417 vref(newfdp->fd_rdir);
2418 cache_copy(&fdp->fd_nrdir, &newfdp->fd_nrdir);
2420 if ((newfdp->fd_jdir = fdp->fd_jdir) != NULL) {
2421 vref(newfdp->fd_jdir);
2422 cache_copy(&fdp->fd_njdir, &newfdp->fd_njdir);
2424 newfdp->fd_refcnt = 1;
2425 newfdp->fd_nfiles = i;
2426 newfdp->fd_lastfile = fdp->fd_lastfile;
2427 newfdp->fd_freefile = fdp->fd_freefile;
2428 newfdp->fd_cmask = fdp->fd_cmask;
2429 spin_init(&newfdp->fd_spin, "fdcopy");
2432 * Copy the descriptor table through (i). This also copies the
2433 * allocation state. Then go through and ref the file pointers
2434 * and clean up any KQ descriptors.
2436 * kq descriptors cannot be copied. Since we haven't ref'd the
2437 * copied files yet we can ignore the return value from funsetfd().
2439 * The read spinlock on fdp is still being held.
2441 * Be sure to clean out fdnode->tdcache, otherwise bad things will
2444 bcopy(fdp->fd_files, newfdp->fd_files, i * sizeof(struct fdnode));
2445 for (i = 0 ; i < newfdp->fd_nfiles; ++i) {
2446 fdnode = &newfdp->fd_files[i];
2447 if (fdnode->reserved) {
2448 fdreserve_locked(newfdp, i, -1);
2449 fdnode->reserved = 0;
2450 fdfixup_locked(newfdp, i);
2451 } else if (fdnode->fp) {
2452 bzero(&fdnode->tdcache, sizeof(fdnode->tdcache));
2453 if (fdnode->fp->f_type == DTYPE_KQUEUE) {
2454 (void)funsetfd_locked(newfdp, i);
2460 spin_unlock(&fdp->fd_spin);
2466 * Release a filedesc structure.
2468 * NOT MPSAFE (MPSAFE for refs > 1, but the final cleanup code is not MPSAFE)
2471 fdfree(struct proc *p, struct filedesc *repl)
2473 struct filedesc *fdp;
2474 struct fdnode *fdnode;
2476 struct filedesc_to_leader *fdtol;
2482 * Before destroying or replacing p->p_fd we must be sure to
2483 * clean out the cache of the last thread, which should be
2486 fexitcache(curthread);
2489 * Certain daemons might not have file descriptors.
2498 * Severe messing around to follow.
2500 spin_lock(&fdp->fd_spin);
2502 /* Check for special need to clear POSIX style locks */
2504 if (fdtol != NULL) {
2505 KASSERT(fdtol->fdl_refcount > 0,
2506 ("filedesc_to_refcount botch: fdl_refcount=%d",
2507 fdtol->fdl_refcount));
2508 if (fdtol->fdl_refcount == 1 && p->p_leader->p_advlock_flag) {
2509 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2510 fdnode = &fdp->fd_files[i];
2511 if (fdnode->fp == NULL ||
2512 fdnode->fp->f_type != DTYPE_VNODE) {
2517 spin_unlock(&fdp->fd_spin);
2519 lf.l_whence = SEEK_SET;
2522 lf.l_type = F_UNLCK;
2523 vp = (struct vnode *)fp->f_data;
2524 VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
2525 F_UNLCK, &lf, F_POSIX);
2527 spin_lock(&fdp->fd_spin);
2531 if (fdtol->fdl_refcount == 1) {
2532 if (fdp->fd_holdleaderscount > 0 &&
2533 p->p_leader->p_advlock_flag) {
2535 * close() or do_dup() has cleared a reference
2536 * in a shared file descriptor table.
2538 fdp->fd_holdleaderswakeup = 1;
2539 ssleep(&fdp->fd_holdleaderscount,
2540 &fdp->fd_spin, 0, "fdlhold", 0);
2543 if (fdtol->fdl_holdcount > 0) {
2545 * Ensure that fdtol->fdl_leader
2546 * remains valid in closef().
2548 fdtol->fdl_wakeup = 1;
2549 ssleep(fdtol, &fdp->fd_spin, 0, "fdlhold", 0);
2553 fdtol->fdl_refcount--;
2554 if (fdtol->fdl_refcount == 0 &&
2555 fdtol->fdl_holdcount == 0) {
2556 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2557 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2562 if (fdtol != NULL) {
2563 spin_unlock(&fdp->fd_spin);
2564 kfree(fdtol, M_FILEDESC_TO_LEADER);
2565 spin_lock(&fdp->fd_spin);
2568 if (--fdp->fd_refcnt > 0) {
2569 spin_unlock(&fdp->fd_spin);
2570 spin_lock(&p->p_spin);
2572 spin_unlock(&p->p_spin);
2577 * Even though we are the last reference to the structure allproc
2578 * scans may still reference the structure. Maintain proper
2579 * locks until we can replace p->p_fd.
2581 * Also note that kqueue's closef still needs to reference the
2582 * fdp via p->p_fd, so we have to close the descriptors before
2583 * we replace p->p_fd.
2585 for (i = 0; i <= fdp->fd_lastfile; ++i) {
2586 if (fdp->fd_files[i].fp) {
2587 fp = funsetfd_locked(fdp, i);
2589 spin_unlock(&fdp->fd_spin);
2590 if (SLIST_FIRST(&fp->f_klist))
2591 knote_fdclose(fp, fdp, i);
2593 spin_lock(&fdp->fd_spin);
2597 spin_unlock(&fdp->fd_spin);
2600 * Interlock against an allproc scan operations (typically frevoke).
2602 spin_lock(&p->p_spin);
2604 spin_unlock(&p->p_spin);
2607 * Wait for any softrefs to go away. This race rarely occurs so
2608 * we can use a non-critical-path style poll/sleep loop. The
2609 * race only occurs against allproc scans.
2611 * No new softrefs can occur with the fdp disconnected from the
2614 if (fdp->fd_softrefs) {
2615 kprintf("pid %d: Warning, fdp race avoided\n", p->p_pid);
2616 while (fdp->fd_softrefs)
2617 tsleep(&fdp->fd_softrefs, 0, "fdsoft", 1);
2620 if (fdp->fd_files != fdp->fd_builtin_files)
2621 kfree(fdp->fd_files, M_FILEDESC);
2623 cache_drop(&fdp->fd_ncdir);
2624 vrele(fdp->fd_cdir);
2627 cache_drop(&fdp->fd_nrdir);
2628 vrele(fdp->fd_rdir);
2631 cache_drop(&fdp->fd_njdir);
2632 vrele(fdp->fd_jdir);
2634 kfree(fdp, M_FILEDESC);
2638 * Retrieve and reference the file pointer associated with a descriptor.
2640 * td must be the current thread.
2643 holdfp(thread_t td, int fd, int flag)
2647 fp = _holdfp_cache(td, fd);
2649 if ((fp->f_flag & flag) == 0 && flag != -1) {
2658 * holdsock() - load the struct file pointer associated
2659 * with a socket into *fpp. If an error occurs, non-zero
2660 * will be returned and *fpp will be set to NULL.
2662 * td must be the current thread.
2665 holdsock(thread_t td, int fd, struct file **fpp)
2673 fp = _holdfp_cache(td, fd);
2675 if (fp->f_type != DTYPE_SOCKET) {
2691 * Convert a user file descriptor to a held file pointer.
2693 * td must be the current thread.
2696 holdvnode(thread_t td, int fd, struct file **fpp)
2701 fp = _holdfp_cache(td, fd);
2703 if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
2719 * For setugid programs, we don't want to people to use that setugidness
2720 * to generate error messages which write to a file which otherwise would
2721 * otherwise be off-limits to the process.
2723 * This is a gross hack to plug the hole. A better solution would involve
2724 * a special vop or other form of generalized access control mechanism. We
2725 * go ahead and just reject all procfs file systems accesses as dangerous.
2727 * Since setugidsafety calls this only for fd 0, 1 and 2, this check is
2728 * sufficient. We also don't for check setugidness since we know we are.
2731 is_unsafe(struct file *fp)
2733 if (fp->f_type == DTYPE_VNODE &&
2734 ((struct vnode *)(fp->f_data))->v_tag == VT_PROCFS)
2740 * Make this setguid thing safe, if at all possible.
2742 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
2745 setugidsafety(struct proc *p)
2747 struct filedesc *fdp = p->p_fd;
2750 /* Certain daemons might not have file descriptors. */
2755 * note: fdp->fd_files may be reallocated out from under us while
2756 * we are blocked in a close. Be careful!
2758 for (i = 0; i <= fdp->fd_lastfile; i++) {
2761 if (fdp->fd_files[i].fp && is_unsafe(fdp->fd_files[i].fp)) {
2765 * NULL-out descriptor prior to close to avoid
2766 * a race while close blocks.
2768 if ((fp = funsetfd_locked(fdp, i)) != NULL) {
2769 knote_fdclose(fp, fdp, i);
2777 * Close all CLOEXEC files on exec.
2779 * Only a single thread remains for the current process.
2781 * NOT MPSAFE - scans fdp without spinlocks, calls knote_fdclose()
2784 fdcloseexec(struct proc *p)
2786 struct filedesc *fdp = p->p_fd;
2789 /* Certain daemons might not have file descriptors. */
2794 * We cannot cache fd_files since operations may block and rip
2795 * them out from under us.
2797 for (i = 0; i <= fdp->fd_lastfile; i++) {
2798 if (fdp->fd_files[i].fp != NULL &&
2799 (fdp->fd_files[i].fileflags & UF_EXCLOSE)) {
2803 * NULL-out descriptor prior to close to avoid
2804 * a race while close blocks.
2806 * (funsetfd*() also clears the fd cache)
2808 if ((fp = funsetfd_locked(fdp, i)) != NULL) {
2809 knote_fdclose(fp, fdp, i);
2817 * It is unsafe for set[ug]id processes to be started with file
2818 * descriptors 0..2 closed, as these descriptors are given implicit
2819 * significance in the Standard C library. fdcheckstd() will create a
2820 * descriptor referencing /dev/null for each of stdin, stdout, and
2821 * stderr that is not already open.
2823 * NOT MPSAFE - calls falloc, vn_open, etc
2826 fdcheckstd(struct lwp *lp)
2828 struct nlookupdata nd;
2829 struct filedesc *fdp;
2832 int i, error, flags, devnull;
2834 fdp = lp->lwp_proc->p_fd;
2839 for (i = 0; i < 3; i++) {
2840 if (fdp->fd_files[i].fp != NULL)
2843 if ((error = falloc(lp, &fp, &devnull)) != 0)
2846 error = nlookup_init(&nd, "/dev/null", UIO_SYSSPACE,
2847 NLC_FOLLOW|NLC_LOCKVP);
2848 flags = FREAD | FWRITE;
2850 error = vn_open(&nd, fp, flags, 0);
2852 fsetfd(fdp, fp, devnull);
2854 fsetfd(fdp, NULL, devnull);
2859 KKASSERT(i == devnull);
2861 error = kern_dup(DUP_FIXED, devnull, i, &retval);
2870 * Internal form of close.
2871 * Decrement reference count on file structure.
2872 * Note: td and/or p may be NULL when closing a file
2873 * that was being passed in a message.
2875 * MPALMOSTSAFE - acquires mplock for VOP operations
2878 closef(struct file *fp, struct proc *p)
2882 struct filedesc_to_leader *fdtol;
2888 * POSIX record locking dictates that any close releases ALL
2889 * locks owned by this process. This is handled by setting
2890 * a flag in the unlock to free ONLY locks obeying POSIX
2891 * semantics, and not to free BSD-style file locks.
2892 * If the descriptor was in a message, POSIX-style locks
2893 * aren't passed with the descriptor.
2895 if (p != NULL && fp->f_type == DTYPE_VNODE &&
2896 (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
2898 if (p->p_leader->p_advlock_flag) {
2899 lf.l_whence = SEEK_SET;
2902 lf.l_type = F_UNLCK;
2903 vp = (struct vnode *)fp->f_data;
2904 VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
2908 if (fdtol != NULL) {
2909 lwkt_gettoken(&p->p_token);
2912 * Handle special case where file descriptor table
2913 * is shared between multiple process leaders.
2915 for (fdtol = fdtol->fdl_next;
2916 fdtol != p->p_fdtol;
2917 fdtol = fdtol->fdl_next) {
2918 if (fdtol->fdl_leader->p_advlock_flag == 0)
2920 fdtol->fdl_holdcount++;
2921 lf.l_whence = SEEK_SET;
2924 lf.l_type = F_UNLCK;
2925 vp = (struct vnode *)fp->f_data;
2926 VOP_ADVLOCK(vp, (caddr_t)fdtol->fdl_leader,
2927 F_UNLCK, &lf, F_POSIX);
2928 fdtol->fdl_holdcount--;
2929 if (fdtol->fdl_holdcount == 0 &&
2930 fdtol->fdl_wakeup != 0) {
2931 fdtol->fdl_wakeup = 0;
2935 lwkt_reltoken(&p->p_token);
2942 * fhold() can only be called if f_count is already at least 1 (i.e. the
2943 * caller of fhold() already has a reference to the file pointer in some
2946 * Atomic ops are used for incrementing and decrementing f_count before
2947 * the 1->0 transition. f_count 1->0 transition is special, see the
2948 * comment in fdrop().
2951 fhold(struct file *fp)
2953 /* 0->1 transition will never work */
2954 KASSERT(fp->f_count > 0, ("fhold: invalid f_count %d", fp->f_count));
2955 atomic_add_int(&fp->f_count, 1);
2959 * fdrop() - drop a reference to a descriptor
2962 fdrop(struct file *fp)
2966 int error, do_free = 0;
2970 * Simple atomic_fetchadd_int(f_count, -1) here will cause use-
2971 * after-free or double free (due to f_count 0->1 transition), if
2972 * fhold() is called on the fps found through filehead iteration.
2975 int count = fp->f_count;
2978 KASSERT(count > 0, ("fdrop: invalid f_count %d", count));
2980 struct filelist_head *head = fp2filelist(fp);
2983 * About to drop the last reference, hold the
2984 * filehead spin lock and drop it, so that no
2985 * one could see this fp through filehead anymore,
2986 * let alone fhold() this fp.
2988 spin_lock(&head->spin);
2989 if (atomic_cmpset_int(&fp->f_count, count, 0)) {
2990 LIST_REMOVE(fp, f_list);
2991 spin_unlock(&head->spin);
2992 atomic_subtract_int(&nfiles, 1);
2993 do_free = 1; /* free this fp */
2996 spin_unlock(&head->spin);
2998 } else if (atomic_cmpset_int(&fp->f_count, count, count - 1)) {
3006 KKASSERT(SLIST_FIRST(&fp->f_klist) == NULL);
3009 * The last reference has gone away, we own the fp structure free
3012 if (fp->f_count < 0)
3013 panic("fdrop: count < 0");
3014 if ((fp->f_flag & FHASLOCK) && fp->f_type == DTYPE_VNODE &&
3015 (((struct vnode *)fp->f_data)->v_flag & VMAYHAVELOCKS)
3017 lf.l_whence = SEEK_SET;
3020 lf.l_type = F_UNLCK;
3021 vp = (struct vnode *)fp->f_data;
3022 VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
3024 if (fp->f_ops != &badfileops)
3025 error = fo_close(fp);
3033 * Apply an advisory lock on a file descriptor.
3035 * Just attempt to get a record lock of the requested type on
3036 * the entire file (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3041 sys_flock(struct flock_args *uap)
3043 thread_t td = curthread;
3049 if ((fp = holdfp(td, uap->fd, -1)) == NULL)
3051 if (fp->f_type != DTYPE_VNODE) {
3055 vp = (struct vnode *)fp->f_data;
3056 lf.l_whence = SEEK_SET;
3059 if (uap->how & LOCK_UN) {
3060 lf.l_type = F_UNLCK;
3061 atomic_clear_int(&fp->f_flag, FHASLOCK); /* race ok */
3062 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, 0);
3065 if (uap->how & LOCK_EX)
3066 lf.l_type = F_WRLCK;
3067 else if (uap->how & LOCK_SH)
3068 lf.l_type = F_RDLCK;
3073 if (uap->how & LOCK_NB)
3074 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 0);
3076 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, F_WAIT);
3077 atomic_set_int(&fp->f_flag, FHASLOCK); /* race ok */
3084 * File Descriptor pseudo-device driver (/dev/fd/).
3086 * Opening minor device N dup()s the file (if any) connected to file
3087 * descriptor N belonging to the calling process. Note that this driver
3088 * consists of only the ``open()'' routine, because all subsequent
3089 * references to this file will be direct to the other driver.
3092 fdopen(struct dev_open_args *ap)
3094 thread_t td = curthread;
3096 KKASSERT(td->td_lwp != NULL);
3099 * XXX Kludge: set curlwp->lwp_dupfd to contain the value of the
3100 * the file descriptor being sought for duplication. The error
3101 * return ensures that the vnode for this device will be released
3102 * by vn_open. Open will detect this special error and take the
3103 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3104 * will simply report the error.
3106 td->td_lwp->lwp_dupfd = minor(ap->a_head.a_dev);
3111 * The caller has reserved the file descriptor dfd for us. On success we
3112 * must fsetfd() it. On failure the caller will clean it up.
3115 dupfdopen(thread_t td, int dfd, int sfd, int mode, int error)
3117 struct filedesc *fdp;
3122 if ((wfp = holdfp(td, sfd, -1)) == NULL)
3126 * Close a revoke/dup race. Duping a descriptor marked as revoked
3127 * will dup a dummy descriptor instead of the real one.
3129 if (wfp->f_flag & FREVOKED) {
3130 kprintf("Warning: attempt to dup() a revoked descriptor\n");
3133 werror = falloc(NULL, &wfp, NULL);
3138 fdp = td->td_proc->p_fd;
3141 * There are two cases of interest here.
3143 * For ENODEV simply dup sfd to file descriptor dfd and return.
3145 * For ENXIO steal away the file structure from sfd and store it
3146 * dfd. sfd is effectively closed by this operation.
3148 * Any other error code is just returned.
3153 * Check that the mode the file is being opened for is a
3154 * subset of the mode of the existing descriptor.
3156 if (((mode & (FREAD|FWRITE)) | wfp->f_flag) != wfp->f_flag) {
3160 spin_lock(&fdp->fd_spin);
3161 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
3162 fsetfd_locked(fdp, wfp, dfd);
3163 spin_unlock(&fdp->fd_spin);
3168 * Steal away the file pointer from dfd, and stuff it into indx.
3170 spin_lock(&fdp->fd_spin);
3171 fdp->fd_files[dfd].fileflags = fdp->fd_files[sfd].fileflags;
3172 fsetfd(fdp, wfp, dfd);
3173 if ((xfp = funsetfd_locked(fdp, sfd)) != NULL) {
3174 spin_unlock(&fdp->fd_spin);
3177 spin_unlock(&fdp->fd_spin);
3189 * NOT MPSAFE - I think these refer to a common file descriptor table
3190 * and we need to spinlock that to link fdtol in.
3192 struct filedesc_to_leader *
3193 filedesc_to_leader_alloc(struct filedesc_to_leader *old,
3194 struct proc *leader)
3196 struct filedesc_to_leader *fdtol;
3198 fdtol = kmalloc(sizeof(struct filedesc_to_leader),
3199 M_FILEDESC_TO_LEADER, M_WAITOK | M_ZERO);
3200 fdtol->fdl_refcount = 1;
3201 fdtol->fdl_holdcount = 0;
3202 fdtol->fdl_wakeup = 0;
3203 fdtol->fdl_leader = leader;
3205 fdtol->fdl_next = old->fdl_next;
3206 fdtol->fdl_prev = old;
3207 old->fdl_next = fdtol;
3208 fdtol->fdl_next->fdl_prev = fdtol;
3210 fdtol->fdl_next = fdtol;
3211 fdtol->fdl_prev = fdtol;
3217 * Scan all file pointers in the system. The callback is made with
3218 * the master list spinlock held exclusively.
3221 allfiles_scan_exclusive(int (*callback)(struct file *, void *), void *data)
3225 for (i = 0; i < NFILELIST_HEADS; ++i) {
3226 struct filelist_head *head = &filelist_heads[i];
3229 spin_lock(&head->spin);
3230 LIST_FOREACH(fp, &head->list, f_list) {
3233 res = callback(fp, data);
3237 spin_unlock(&head->spin);
3242 * Get file structures.
3244 * NOT MPSAFE - process list scan, SYSCTL_OUT (probably not mpsafe)
3247 struct sysctl_kern_file_info {
3250 struct sysctl_req *req;
3253 static int sysctl_kern_file_callback(struct proc *p, void *data);
3256 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
3258 struct sysctl_kern_file_info info;
3261 * Note: because the number of file descriptors is calculated
3262 * in different ways for sizing vs returning the data,
3263 * there is information leakage from the first loop. However,
3264 * it is of a similar order of magnitude to the leakage from
3265 * global system statistics such as kern.openfiles.
3267 * When just doing a count, note that we cannot just count
3268 * the elements and add f_count via the filehead list because
3269 * threaded processes share their descriptor table and f_count might
3270 * still be '1' in that case.
3272 * Since the SYSCTL op can block, we must hold the process to
3273 * prevent it being ripped out from under us either in the
3274 * file descriptor loop or in the greater LIST_FOREACH. The
3275 * process may be in varying states of disrepair. If the process
3276 * is in SZOMB we may have caught it just as it is being removed
3277 * from the allproc list, we must skip it in that case to maintain
3278 * an unbroken chain through the allproc list.
3283 allproc_scan(sysctl_kern_file_callback, &info, 0);
3286 * When just calculating the size, overestimate a bit to try to
3287 * prevent system activity from causing the buffer-fill call
3290 if (req->oldptr == NULL) {
3291 info.count = (info.count + 16) + (info.count / 10);
3292 info.error = SYSCTL_OUT(req, NULL,
3293 info.count * sizeof(struct kinfo_file));
3295 return (info.error);
3299 sysctl_kern_file_callback(struct proc *p, void *data)
3301 struct sysctl_kern_file_info *info = data;
3302 struct kinfo_file kf;
3303 struct filedesc *fdp;
3308 if (p->p_stat == SIDL || p->p_stat == SZOMB)
3310 if (!(PRISON_CHECK(info->req->td->td_ucred, p->p_ucred) != 0))
3314 * Softref the fdp to prevent it from being destroyed
3316 spin_lock(&p->p_spin);
3317 if ((fdp = p->p_fd) == NULL) {
3318 spin_unlock(&p->p_spin);
3321 atomic_add_int(&fdp->fd_softrefs, 1);
3322 spin_unlock(&p->p_spin);
3325 * The fdp's own spinlock prevents the contents from being
3328 spin_lock_shared(&fdp->fd_spin);
3329 for (n = 0; n < fdp->fd_nfiles; ++n) {
3330 if ((fp = fdp->fd_files[n].fp) == NULL)
3332 if (info->req->oldptr == NULL) {
3335 uid = p->p_ucred ? p->p_ucred->cr_uid : -1;
3336 kcore_make_file(&kf, fp, p->p_pid, uid, n);
3337 spin_unlock_shared(&fdp->fd_spin);
3338 info->error = SYSCTL_OUT(info->req, &kf, sizeof(kf));
3339 spin_lock_shared(&fdp->fd_spin);
3344 spin_unlock_shared(&fdp->fd_spin);
3345 atomic_subtract_int(&fdp->fd_softrefs, 1);
3351 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD,
3352 0, 0, sysctl_kern_file, "S,file", "Entire file table");
3354 SYSCTL_INT(_kern, OID_AUTO, minfilesperproc, CTLFLAG_RW,
3355 &minfilesperproc, 0, "Minimum files allowed open per process");
3356 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3357 &maxfilesperproc, 0, "Maximum files allowed open per process");
3358 SYSCTL_INT(_kern, OID_AUTO, maxfilesperuser, CTLFLAG_RW,
3359 &maxfilesperuser, 0, "Maximum files allowed open per user");
3361 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3362 &maxfiles, 0, "Maximum number of files");
3364 SYSCTL_INT(_kern, OID_AUTO, maxfilesrootres, CTLFLAG_RW,
3365 &maxfilesrootres, 0, "Descriptors reserved for root use");
3367 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3368 &nfiles, 0, "System-wide number of open files");
3371 fildesc_drvinit(void *unused)
3375 for (fd = 0; fd < NUMFDESC; fd++) {
3376 make_dev(&fildesc_ops, fd,
3377 UID_BIN, GID_BIN, 0666, "fd/%d", fd);
3380 make_dev(&fildesc_ops, 0, UID_ROOT, GID_WHEEL, 0666, "stdin");
3381 make_dev(&fildesc_ops, 1, UID_ROOT, GID_WHEEL, 0666, "stdout");
3382 make_dev(&fildesc_ops, 2, UID_ROOT, GID_WHEEL, 0666, "stderr");
3385 struct fileops badfileops = {
3386 .fo_read = badfo_readwrite,
3387 .fo_write = badfo_readwrite,
3388 .fo_ioctl = badfo_ioctl,
3389 .fo_kqfilter = badfo_kqfilter,
3390 .fo_stat = badfo_stat,
3391 .fo_close = badfo_close,
3392 .fo_shutdown = badfo_shutdown
3406 badfo_ioctl(struct file *fp, u_long com, caddr_t data,
3407 struct ucred *cred, struct sysmsg *msgv)
3413 * Must return an error to prevent registration, typically
3414 * due to a revoked descriptor (file_filtops assigned).
3417 badfo_kqfilter(struct file *fp, struct knote *kn)
3419 return (EOPNOTSUPP);
3423 badfo_stat(struct file *fp, struct stat *sb, struct ucred *cred)
3429 badfo_close(struct file *fp)
3435 badfo_shutdown(struct file *fp, int how)
3441 nofo_shutdown(struct file *fp, int how)
3443 return (EOPNOTSUPP);
3446 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE + CDEV_MAJOR,
3447 fildesc_drvinit,NULL);
3450 filelist_heads_init(void *arg __unused)
3454 for (i = 0; i < NFILELIST_HEADS; ++i) {
3455 struct filelist_head *head = &filelist_heads[i];
3457 spin_init(&head->spin, "filehead_spin");
3458 LIST_INIT(&head->list);
3462 SYSINIT(filelistheads, SI_BOOT1_LOCK, SI_ORDER_ANY,
3463 filelist_heads_init, NULL);
3466 file_objcache_init(void *dummy __unused)
3468 file_objcache = objcache_create("file", maxfiles, maxfiles / 8,
3469 NULL, NULL, NULL, /* TODO: ctor/dtor */
3470 objcache_malloc_alloc, objcache_malloc_free, &file_malloc_args);
3472 SYSINIT(fpobjcache, SI_BOOT2_POST_SMP, SI_ORDER_ANY, file_objcache_init, NULL);