2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_capsicum.h"
41 #include "opt_compat.h"
43 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/capsicum.h>
50 #include <sys/fcntl.h>
52 #include <sys/filedesc.h>
53 #include <sys/filio.h>
55 #include <sys/kernel.h>
56 #include <sys/limits.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/mutex.h>
61 #include <sys/namei.h>
62 #include <sys/selinfo.h>
65 #include <sys/protosw.h>
66 #include <sys/racct.h>
67 #include <sys/resourcevar.h>
69 #include <sys/signalvar.h>
70 #include <sys/socketvar.h>
73 #include <sys/syscallsubr.h>
74 #include <sys/sysctl.h>
75 #include <sys/sysproto.h>
76 #include <sys/unistd.h>
78 #include <sys/vnode.h>
80 #include <sys/ktrace.h>
85 #include <security/audit/audit.h>
92 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
93 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
94 "file desc to leader structures");
95 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
96 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
98 MALLOC_DECLARE(M_FADVISE);
100 static uma_zone_t file_zone;
101 static uma_zone_t filedesc0_zone;
103 static int closefp(struct filedesc *fdp, int fd, struct file *fp,
104 struct thread *td, int holdleaders);
105 static int do_dup(struct thread *td, int flags, int old, int new);
106 static int fd_first_free(struct filedesc *fdp, int low, int size);
107 static int fd_last_used(struct filedesc *fdp, int size);
108 static void fdgrowtable(struct filedesc *fdp, int nfd);
109 static void fdgrowtable_exp(struct filedesc *fdp, int nfd);
110 static void fdunused(struct filedesc *fdp, int fd);
111 static void fdused(struct filedesc *fdp, int fd);
112 static int getmaxfd(struct thread *td);
114 /* Flags for do_dup() */
115 #define DUP_FIXED 0x1 /* Force fixed allocation. */
116 #define DUP_FCNTL 0x2 /* fcntl()-style errors. */
117 #define DUP_CLOEXEC 0x4 /* Atomically set FD_CLOEXEC. */
122 * - An array of open file descriptors (fd_ofiles)
123 * - An array of file flags (fd_ofileflags)
124 * - A bitmap recording which descriptors are in use (fd_map)
126 * A process starts out with NDFILE descriptors. The value of NDFILE has
127 * been selected based the historical limit of 20 open files, and an
128 * assumption that the majority of processes, especially short-lived
129 * processes like shells, will never need more.
131 * If this initial allocation is exhausted, a larger descriptor table and
132 * map are allocated dynamically, and the pointers in the process's struct
133 * filedesc are updated to point to those. This is repeated every time
134 * the process runs out of file descriptors (provided it hasn't hit its
137 * Since threads may hold references to individual descriptor table
138 * entries, the tables are never freed. Instead, they are placed on a
139 * linked list and freed only when the struct filedesc is released.
142 #define NDSLOTSIZE sizeof(NDSLOTTYPE)
143 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT)
144 #define NDSLOT(x) ((x) / NDENTRIES)
145 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES))
146 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES)
149 * SLIST entry used to keep track of ofiles which must be reclaimed when
153 struct fdescenttbl *ft_table;
154 SLIST_ENTRY(freetable) ft_next;
158 * Initial allocation: a filedesc structure + the head of SLIST used to
159 * keep track of old ofiles + enough space for NDFILE descriptors.
162 struct fdescenttbl0 {
164 struct filedescent fdt_ofiles[NDFILE];
168 struct filedesc fd_fd;
169 SLIST_HEAD(, freetable) fd_free;
170 struct fdescenttbl0 fd_dfiles;
171 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
175 * Descriptor management.
177 volatile int openfiles; /* actual number of open files */
178 struct mtx sigio_lock; /* mtx to protect pointers to sigio */
179 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
182 * If low >= size, just return low. Otherwise find the first zero bit in the
183 * given bitmap, starting at low and not exceeding size - 1. Return size if
187 fd_first_free(struct filedesc *fdp, int low, int size)
189 NDSLOTTYPE *map = fdp->fd_map;
197 if (low % NDENTRIES) {
198 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
199 if ((mask &= ~map[off]) != 0UL)
200 return (off * NDENTRIES + ffsl(mask) - 1);
203 for (maxoff = NDSLOTS(size); off < maxoff; ++off)
204 if (map[off] != ~0UL)
205 return (off * NDENTRIES + ffsl(~map[off]) - 1);
210 * Find the highest non-zero bit in the given bitmap, starting at 0 and
211 * not exceeding size - 1. Return -1 if not found.
214 fd_last_used(struct filedesc *fdp, int size)
216 NDSLOTTYPE *map = fdp->fd_map;
221 if (size % NDENTRIES) {
222 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES));
223 if ((mask &= map[off]) != 0)
224 return (off * NDENTRIES + flsl(mask) - 1);
227 for (minoff = NDSLOT(0); off >= minoff; --off)
229 return (off * NDENTRIES + flsl(map[off]) - 1);
235 fdisused(struct filedesc *fdp, int fd)
238 KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
239 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
241 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
246 * Mark a file descriptor as used.
249 fdused_init(struct filedesc *fdp, int fd)
252 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
254 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
258 fdused(struct filedesc *fdp, int fd)
261 FILEDESC_XLOCK_ASSERT(fdp);
263 fdused_init(fdp, fd);
264 if (fd > fdp->fd_lastfile)
265 fdp->fd_lastfile = fd;
266 if (fd == fdp->fd_freefile)
267 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles);
271 * Mark a file descriptor as unused.
274 fdunused(struct filedesc *fdp, int fd)
277 FILEDESC_XLOCK_ASSERT(fdp);
279 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
280 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
281 ("fd=%d is still in use", fd));
283 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
284 if (fd < fdp->fd_freefile)
285 fdp->fd_freefile = fd;
286 if (fd == fdp->fd_lastfile)
287 fdp->fd_lastfile = fd_last_used(fdp, fd);
291 * Free a file descriptor.
293 * Avoid some work if fdp is about to be destroyed.
296 fdefree_last(struct filedescent *fde)
299 filecaps_free(&fde->fde_caps);
303 fdfree(struct filedesc *fdp, int fd)
305 struct filedescent *fde;
307 fde = &fdp->fd_ofiles[fd];
309 seq_write_begin(&fde->fde_seq);
312 fde->fde_file = NULL;
315 seq_write_end(&fde->fde_seq);
320 * System calls on descriptors.
322 #ifndef _SYS_SYSPROTO_H_
323 struct getdtablesize_args {
329 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
336 min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc);
338 PROC_LOCK(td->td_proc);
339 lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
340 PROC_UNLOCK(td->td_proc);
341 if (lim < td->td_retval[0])
342 td->td_retval[0] = lim;
348 * Duplicate a file descriptor to a particular value.
350 * Note: keep in mind that a potential race condition exists when closing
351 * descriptors from a shared descriptor table (via rfork).
353 #ifndef _SYS_SYSPROTO_H_
361 sys_dup2(struct thread *td, struct dup2_args *uap)
364 return (do_dup(td, DUP_FIXED, (int)uap->from, (int)uap->to));
368 * Duplicate a file descriptor.
370 #ifndef _SYS_SYSPROTO_H_
377 sys_dup(struct thread *td, struct dup_args *uap)
380 return (do_dup(td, 0, (int)uap->fd, 0));
384 * The file control system call.
386 #ifndef _SYS_SYSPROTO_H_
395 sys_fcntl(struct thread *td, struct fcntl_args *uap)
398 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
402 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg)
415 * Convert old flock structure to new.
417 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl));
418 fl.l_start = ofl.l_start;
419 fl.l_len = ofl.l_len;
420 fl.l_pid = ofl.l_pid;
421 fl.l_type = ofl.l_type;
422 fl.l_whence = ofl.l_whence;
436 arg1 = (intptr_t)&fl;
442 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl));
443 arg1 = (intptr_t)&fl;
451 error = kern_fcntl(td, fd, cmd, arg1);
454 if (cmd == F_OGETLK) {
455 ofl.l_start = fl.l_start;
456 ofl.l_len = fl.l_len;
457 ofl.l_pid = fl.l_pid;
458 ofl.l_type = fl.l_type;
459 ofl.l_whence = fl.l_whence;
460 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl));
461 } else if (cmd == F_GETLK) {
462 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl));
468 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
470 struct filedesc *fdp;
472 struct file *fp, *fp2;
473 struct filedescent *fde;
489 error = do_dup(td, DUP_FCNTL, fd, tmp);
492 case F_DUPFD_CLOEXEC:
494 error = do_dup(td, DUP_FCNTL | DUP_CLOEXEC, fd, tmp);
499 error = do_dup(td, DUP_FIXED, fd, tmp);
502 case F_DUP2FD_CLOEXEC:
504 error = do_dup(td, DUP_FIXED | DUP_CLOEXEC, fd, tmp);
509 if (fget_locked(fdp, fd) == NULL) {
510 FILEDESC_SUNLOCK(fdp);
514 fde = &fdp->fd_ofiles[fd];
516 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
517 FILEDESC_SUNLOCK(fdp);
522 if (fget_locked(fdp, fd) == NULL) {
523 FILEDESC_XUNLOCK(fdp);
527 fde = &fdp->fd_ofiles[fd];
528 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
529 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
530 FILEDESC_XUNLOCK(fdp);
534 error = fget_fcntl(td, fd,
535 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp);
538 td->td_retval[0] = OFLAGS(fp->f_flag);
543 error = fget_fcntl(td, fd,
544 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp);
548 tmp = flg = fp->f_flag;
550 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
551 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
552 tmp = fp->f_flag & FNONBLOCK;
553 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
558 tmp = fp->f_flag & FASYNC;
559 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
564 atomic_clear_int(&fp->f_flag, FNONBLOCK);
566 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
571 error = fget_fcntl(td, fd,
572 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp);
575 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
577 td->td_retval[0] = tmp;
582 error = fget_fcntl(td, fd,
583 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp);
587 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
592 error = priv_check(td, PRIV_NFS_LOCKD);
600 /* FALLTHROUGH F_SETLK */
604 cap_rights_init(&rights, CAP_FLOCK);
605 error = fget_unlocked(fdp, fd, &rights, &fp, NULL);
608 if (fp->f_type != DTYPE_VNODE) {
614 flp = (struct flock *)arg;
615 if (flp->l_whence == SEEK_CUR) {
616 foffset = foffset_get(fp);
619 foffset > OFF_MAX - flp->l_start)) {
624 flp->l_start += foffset;
628 switch (flp->l_type) {
630 if ((fp->f_flag & FREAD) == 0) {
634 PROC_LOCK(p->p_leader);
635 p->p_leader->p_flag |= P_ADVLOCK;
636 PROC_UNLOCK(p->p_leader);
637 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
641 if ((fp->f_flag & FWRITE) == 0) {
645 PROC_LOCK(p->p_leader);
646 p->p_leader->p_flag |= P_ADVLOCK;
647 PROC_UNLOCK(p->p_leader);
648 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
652 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
657 * Temporary api for testing remote lock
660 if (flg != F_REMOTE) {
664 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
665 F_UNLCKSYS, flp, flg);
671 if (error != 0 || flp->l_type == F_UNLCK ||
672 flp->l_type == F_UNLCKSYS) {
678 * Check for a race with close.
680 * The vnode is now advisory locked (or unlocked, but this case
681 * is not really important) as the caller requested.
682 * We had to drop the filedesc lock, so we need to recheck if
683 * the descriptor is still valid, because if it was closed
684 * in the meantime we need to remove advisory lock from the
685 * vnode - close on any descriptor leading to an advisory
686 * locked vnode, removes that lock.
687 * We will return 0 on purpose in that case, as the result of
688 * successful advisory lock might have been externally visible
689 * already. This is fine - effectively we pretend to the caller
690 * that the closing thread was a bit slower and that the
691 * advisory lock succeeded before the close.
693 error = fget_unlocked(fdp, fd, &rights, &fp2, NULL);
699 flp->l_whence = SEEK_SET;
702 flp->l_type = F_UNLCK;
703 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
704 F_UNLCK, flp, F_POSIX);
711 error = fget_unlocked(fdp, fd,
712 cap_rights_init(&rights, CAP_FLOCK), &fp, NULL);
715 if (fp->f_type != DTYPE_VNODE) {
720 flp = (struct flock *)arg;
721 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
722 flp->l_type != F_UNLCK) {
727 if (flp->l_whence == SEEK_CUR) {
728 foffset = foffset_get(fp);
729 if ((flp->l_start > 0 &&
730 foffset > OFF_MAX - flp->l_start) ||
732 foffset < OFF_MIN - flp->l_start)) {
737 flp->l_start += foffset;
740 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
746 arg = arg ? 128 * 1024: 0;
749 error = fget_unlocked(fdp, fd,
750 cap_rights_init(&rights), &fp, NULL);
753 if (fp->f_type != DTYPE_VNODE) {
760 * Exclusive lock synchronizes against f_seqcount reads and
761 * writes in sequential_heuristic().
763 error = vn_lock(vp, LK_EXCLUSIVE);
769 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
770 fp->f_seqcount = (arg + bsize - 1) / bsize;
771 atomic_set_int(&fp->f_flag, FRDAHEAD);
773 atomic_clear_int(&fp->f_flag, FRDAHEAD);
787 getmaxfd(struct thread *td)
790 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
794 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
797 do_dup(struct thread *td, int flags, int old, int new)
799 struct filedesc *fdp;
800 struct filedescent *oldfde, *newfde;
810 * Verify we have a valid descriptor to dup from and possibly to
811 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
812 * return EINVAL when the new descriptor is out of bounds.
817 return (flags & DUP_FCNTL ? EINVAL : EBADF);
818 maxfd = getmaxfd(td);
820 return (flags & DUP_FCNTL ? EINVAL : EBADF);
823 if (fget_locked(fdp, old) == NULL) {
824 FILEDESC_XUNLOCK(fdp);
827 oldfde = &fdp->fd_ofiles[old];
828 if (flags & DUP_FIXED && old == new) {
829 td->td_retval[0] = new;
830 if (flags & DUP_CLOEXEC)
831 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
832 FILEDESC_XUNLOCK(fdp);
835 fp = oldfde->fde_file;
839 * If the caller specified a file descriptor, make sure the file
840 * table is large enough to hold it, and grab it. Otherwise, just
841 * allocate a new descriptor the usual way.
843 if (flags & DUP_FIXED) {
844 if (new >= fdp->fd_nfiles) {
846 * The resource limits are here instead of e.g.
847 * fdalloc(), because the file descriptor table may be
848 * shared between processes, so we can't really use
849 * racct_add()/racct_sub(). Instead of counting the
850 * number of actually allocated descriptors, just put
851 * the limit on the size of the file descriptor table.
856 error = racct_set(p, RACCT_NOFILE, new + 1);
859 FILEDESC_XUNLOCK(fdp);
865 fdgrowtable_exp(fdp, new + 1);
866 oldfde = &fdp->fd_ofiles[old];
868 newfde = &fdp->fd_ofiles[new];
869 if (newfde->fde_file == NULL)
872 if ((error = fdalloc(td, new, &new)) != 0) {
873 FILEDESC_XUNLOCK(fdp);
877 newfde = &fdp->fd_ofiles[new];
880 KASSERT(fp == oldfde->fde_file, ("old fd has been modified"));
881 KASSERT(old != new, ("new fd is same as old"));
883 delfp = newfde->fde_file;
886 * Duplicate the source descriptor.
889 seq_write_begin(&newfde->fde_seq);
891 filecaps_free(&newfde->fde_caps);
892 memcpy(newfde, oldfde, fde_change_size);
893 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
894 if ((flags & DUP_CLOEXEC) != 0)
895 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
897 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
899 seq_write_end(&newfde->fde_seq);
901 td->td_retval[0] = new;
904 (void) closefp(fdp, new, delfp, td, 1);
905 /* closefp() drops the FILEDESC lock for us. */
907 FILEDESC_XUNLOCK(fdp);
914 * If sigio is on the list associated with a process or process group,
915 * disable signalling from the device, remove sigio from the list and
919 funsetown(struct sigio **sigiop)
929 *(sigio->sio_myref) = NULL;
930 if ((sigio)->sio_pgid < 0) {
931 struct pgrp *pg = (sigio)->sio_pgrp;
933 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio,
937 struct proc *p = (sigio)->sio_proc;
939 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio,
944 crfree(sigio->sio_ucred);
945 free(sigio, M_SIGIO);
949 * Free a list of sigio structures.
950 * We only need to lock the SIGIO_LOCK because we have made ourselves
951 * inaccessible to callers of fsetown and therefore do not need to lock
952 * the proc or pgrp struct for the list manipulation.
955 funsetownlst(struct sigiolst *sigiolst)
961 sigio = SLIST_FIRST(sigiolst);
968 * Every entry of the list should belong
969 * to a single proc or pgrp.
971 if (sigio->sio_pgid < 0) {
972 pg = sigio->sio_pgrp;
973 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED);
974 } else /* if (sigio->sio_pgid > 0) */ {
976 PROC_LOCK_ASSERT(p, MA_NOTOWNED);
980 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) {
981 *(sigio->sio_myref) = NULL;
983 KASSERT(sigio->sio_pgid < 0,
984 ("Proc sigio in pgrp sigio list"));
985 KASSERT(sigio->sio_pgrp == pg,
986 ("Bogus pgrp in sigio list"));
988 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio,
991 } else /* if (p != NULL) */ {
992 KASSERT(sigio->sio_pgid > 0,
993 ("Pgrp sigio in proc sigio list"));
994 KASSERT(sigio->sio_proc == p,
995 ("Bogus proc in sigio list"));
997 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio,
1002 crfree(sigio->sio_ucred);
1003 free(sigio, M_SIGIO);
1010 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1012 * After permission checking, add a sigio structure to the sigio list for
1013 * the process or process group.
1016 fsetown(pid_t pgid, struct sigio **sigiop)
1020 struct sigio *sigio;
1030 /* Allocate and fill in the new sigio out of locks. */
1031 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1032 sigio->sio_pgid = pgid;
1033 sigio->sio_ucred = crhold(curthread->td_ucred);
1034 sigio->sio_myref = sigiop;
1036 sx_slock(&proctree_lock);
1045 * Policy - Don't allow a process to FSETOWN a process
1046 * in another session.
1048 * Remove this test to allow maximum flexibility or
1049 * restrict FSETOWN to the current process or process
1050 * group for maximum safety.
1053 if (proc->p_session != curthread->td_proc->p_session) {
1059 } else /* if (pgid < 0) */ {
1060 pgrp = pgfind(-pgid);
1068 * Policy - Don't allow a process to FSETOWN a process
1069 * in another session.
1071 * Remove this test to allow maximum flexibility or
1072 * restrict FSETOWN to the current process or process
1073 * group for maximum safety.
1075 if (pgrp->pg_session != curthread->td_proc->p_session) {
1086 * Since funsetownlst() is called without the proctree
1087 * locked, we need to check for P_WEXIT.
1088 * XXX: is ESRCH correct?
1090 if ((proc->p_flag & P_WEXIT) != 0) {
1095 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio);
1096 sigio->sio_proc = proc;
1100 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio);
1101 sigio->sio_pgrp = pgrp;
1104 sx_sunlock(&proctree_lock);
1111 sx_sunlock(&proctree_lock);
1112 crfree(sigio->sio_ucred);
1113 free(sigio, M_SIGIO);
1118 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1122 struct sigio **sigiop;
1127 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1133 * Function drops the filedesc lock on return.
1136 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1141 FILEDESC_XLOCK_ASSERT(fdp);
1144 if (td->td_proc->p_fdtol != NULL) {
1146 * Ask fdfree() to sleep to ensure that all relevant
1147 * process leaders can be traversed in closef().
1149 fdp->fd_holdleaderscount++;
1156 * We now hold the fp reference that used to be owned by the
1157 * descriptor array. We have to unlock the FILEDESC *AFTER*
1158 * knote_fdclose to prevent a race of the fd getting opened, a knote
1159 * added, and deleteing a knote for the new fd.
1161 knote_fdclose(td, fd);
1164 * We need to notify mqueue if the object is of type mqueue.
1166 if (fp->f_type == DTYPE_MQUEUE)
1167 mq_fdclose(td, fd, fp);
1168 FILEDESC_XUNLOCK(fdp);
1170 error = closef(fp, td);
1172 FILEDESC_XLOCK(fdp);
1173 fdp->fd_holdleaderscount--;
1174 if (fdp->fd_holdleaderscount == 0 &&
1175 fdp->fd_holdleaderswakeup != 0) {
1176 fdp->fd_holdleaderswakeup = 0;
1177 wakeup(&fdp->fd_holdleaderscount);
1179 FILEDESC_XUNLOCK(fdp);
1185 * Close a file descriptor.
1187 #ifndef _SYS_SYSPROTO_H_
1194 sys_close(struct thread *td, struct close_args *uap)
1197 return (kern_close(td, uap->fd));
1201 kern_close(struct thread *td, int fd)
1203 struct filedesc *fdp;
1206 fdp = td->td_proc->p_fd;
1208 AUDIT_SYSCLOSE(td, fd);
1210 FILEDESC_XLOCK(fdp);
1211 if ((fp = fget_locked(fdp, fd)) == NULL) {
1212 FILEDESC_XUNLOCK(fdp);
1217 /* closefp() drops the FILEDESC lock for us. */
1218 return (closefp(fdp, fd, fp, td, 1));
1222 * Close open file descriptors.
1224 #ifndef _SYS_SYSPROTO_H_
1225 struct closefrom_args {
1231 sys_closefrom(struct thread *td, struct closefrom_args *uap)
1233 struct filedesc *fdp;
1236 fdp = td->td_proc->p_fd;
1237 AUDIT_ARG_FD(uap->lowfd);
1240 * Treat negative starting file descriptor values identical to
1241 * closefrom(0) which closes all files.
1245 FILEDESC_SLOCK(fdp);
1246 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) {
1247 if (fdp->fd_ofiles[fd].fde_file != NULL) {
1248 FILEDESC_SUNLOCK(fdp);
1249 (void)kern_close(td, fd);
1250 FILEDESC_SLOCK(fdp);
1253 FILEDESC_SUNLOCK(fdp);
1257 #if defined(COMPAT_43)
1259 * Return status information about a file descriptor.
1261 #ifndef _SYS_SYSPROTO_H_
1262 struct ofstat_args {
1269 ofstat(struct thread *td, struct ofstat_args *uap)
1275 error = kern_fstat(td, uap->fd, &ub);
1278 error = copyout(&oub, uap->sb, sizeof(oub));
1282 #endif /* COMPAT_43 */
1285 * Return status information about a file descriptor.
1287 #ifndef _SYS_SYSPROTO_H_
1295 sys_fstat(struct thread *td, struct fstat_args *uap)
1300 error = kern_fstat(td, uap->fd, &ub);
1302 error = copyout(&ub, uap->sb, sizeof(ub));
1307 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1310 cap_rights_t rights;
1315 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp);
1319 AUDIT_ARG_FILE(td->td_proc, fp);
1321 error = fo_stat(fp, sbp, td->td_ucred, td);
1324 if (error == 0 && KTRPOINT(td, KTR_STRUCT))
1331 * Return status information about a file descriptor.
1333 #ifndef _SYS_SYSPROTO_H_
1334 struct nfstat_args {
1341 sys_nfstat(struct thread *td, struct nfstat_args *uap)
1347 error = kern_fstat(td, uap->fd, &ub);
1349 cvtnstat(&ub, &nub);
1350 error = copyout(&nub, uap->sb, sizeof(nub));
1356 * Return pathconf information about a file descriptor.
1358 #ifndef _SYS_SYSPROTO_H_
1359 struct fpathconf_args {
1366 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1370 cap_rights_t rights;
1373 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp);
1377 /* If asynchronous I/O is available, it works for all descriptors. */
1378 if (uap->name == _PC_ASYNC_IO) {
1379 td->td_retval[0] = async_io_version;
1384 vn_lock(vp, LK_SHARED | LK_RETRY);
1385 error = VOP_PATHCONF(vp, uap->name, td->td_retval);
1387 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1388 if (uap->name != _PC_PIPE_BUF) {
1391 td->td_retval[0] = PIPE_BUF;
1403 * Initialize filecaps structure.
1406 filecaps_init(struct filecaps *fcaps)
1409 bzero(fcaps, sizeof(*fcaps));
1410 fcaps->fc_nioctls = -1;
1414 * Copy filecaps structure allocating memory for ioctls array if needed.
1417 filecaps_copy(const struct filecaps *src, struct filecaps *dst)
1422 if (src->fc_ioctls != NULL) {
1423 KASSERT(src->fc_nioctls > 0,
1424 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1426 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1427 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1428 bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1433 * Move filecaps structure to the new place and clear the old place.
1436 filecaps_move(struct filecaps *src, struct filecaps *dst)
1440 bzero(src, sizeof(*src));
1444 * Fill the given filecaps structure with full rights.
1447 filecaps_fill(struct filecaps *fcaps)
1450 CAP_ALL(&fcaps->fc_rights);
1451 fcaps->fc_ioctls = NULL;
1452 fcaps->fc_nioctls = -1;
1453 fcaps->fc_fcntls = CAP_FCNTL_ALL;
1457 * Free memory allocated within filecaps structure.
1460 filecaps_free(struct filecaps *fcaps)
1463 free(fcaps->fc_ioctls, M_FILECAPS);
1464 bzero(fcaps, sizeof(*fcaps));
1468 * Validate the given filecaps structure.
1471 filecaps_validate(const struct filecaps *fcaps, const char *func)
1474 KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1475 ("%s: invalid rights", func));
1476 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1477 ("%s: invalid fcntls", func));
1478 KASSERT(fcaps->fc_fcntls == 0 ||
1479 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1480 ("%s: fcntls without CAP_FCNTL", func));
1481 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1482 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1483 ("%s: invalid ioctls", func));
1484 KASSERT(fcaps->fc_nioctls == 0 ||
1485 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1486 ("%s: ioctls without CAP_IOCTL", func));
1490 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1494 FILEDESC_XLOCK_ASSERT(fdp);
1496 nfd1 = fdp->fd_nfiles * 2;
1499 fdgrowtable(fdp, nfd1);
1503 * Grow the file table to accomodate (at least) nfd descriptors.
1506 fdgrowtable(struct filedesc *fdp, int nfd)
1508 struct filedesc0 *fdp0;
1509 struct freetable *ft;
1510 struct fdescenttbl *ntable;
1511 struct fdescenttbl *otable;
1512 int nnfiles, onfiles;
1513 NDSLOTTYPE *nmap, *omap;
1516 * If lastfile is -1 this struct filedesc was just allocated and we are
1517 * growing it to accomodate for the one we are going to copy from. There
1518 * is no need to have a lock on this one as it's not visible to anyone.
1520 if (fdp->fd_lastfile != -1)
1521 FILEDESC_XLOCK_ASSERT(fdp);
1523 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1525 /* save old values */
1526 onfiles = fdp->fd_nfiles;
1527 otable = fdp->fd_files;
1530 /* compute the size of the new table */
1531 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1532 if (nnfiles <= onfiles)
1533 /* the table is already large enough */
1537 * Allocate a new table. We need enough space for the number of
1538 * entries, file entries themselves and the struct freetable we will use
1539 * when we decommission the table and place it on the freelist.
1540 * We place the struct freetable in the middle so we don't have
1541 * to worry about padding.
1543 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1544 nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1545 sizeof(struct freetable),
1546 M_FILEDESC, M_ZERO | M_WAITOK);
1547 /* copy the old data */
1548 ntable->fdt_nfiles = nnfiles;
1549 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1550 onfiles * sizeof(ntable->fdt_ofiles[0]));
1553 * Allocate a new map only if the old is not large enough. It will
1554 * grow at a slower rate than the table as it can map more
1555 * entries than the table can hold.
1557 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1558 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1560 /* copy over the old data and update the pointer */
1561 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1566 * Make sure that ntable is correctly initialized before we replace
1567 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1570 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1573 * Do not free the old file table, as some threads may still
1574 * reference entries within it. Instead, place it on a freelist
1575 * which will be processed when the struct filedesc is released.
1577 * Note that if onfiles == NDFILE, we're dealing with the original
1578 * static allocation contained within (struct filedesc0 *)fdp,
1579 * which must not be freed.
1581 if (onfiles > NDFILE) {
1582 ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1583 fdp0 = (struct filedesc0 *)fdp;
1584 ft->ft_table = otable;
1585 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1588 * The map does not have the same possibility of threads still
1589 * holding references to it. So always free it as long as it
1590 * does not reference the original static allocation.
1592 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1593 free(omap, M_FILEDESC);
1597 * Allocate a file descriptor for the process.
1600 fdalloc(struct thread *td, int minfd, int *result)
1602 struct proc *p = td->td_proc;
1603 struct filedesc *fdp = p->p_fd;
1604 int fd, maxfd, allocfd;
1609 FILEDESC_XLOCK_ASSERT(fdp);
1611 if (fdp->fd_freefile > minfd)
1612 minfd = fdp->fd_freefile;
1614 maxfd = getmaxfd(td);
1617 * Search the bitmap for a free descriptor starting at minfd.
1618 * If none is found, grow the file table.
1620 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
1623 if (fd >= fdp->fd_nfiles) {
1624 allocfd = min(fd * 2, maxfd);
1628 error = racct_set(p, RACCT_NOFILE, allocfd);
1635 * fd is already equal to first free descriptor >= minfd, so
1636 * we only need to grow the table and we are done.
1638 fdgrowtable_exp(fdp, allocfd);
1642 * Perform some sanity checks, then mark the file descriptor as
1643 * used and return it to the caller.
1645 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
1646 ("invalid descriptor %d", fd));
1647 KASSERT(!fdisused(fdp, fd),
1648 ("fd_first_free() returned non-free descriptor"));
1649 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
1650 ("file descriptor isn't free"));
1657 * Allocate n file descriptors for the process.
1660 fdallocn(struct thread *td, int minfd, int *fds, int n)
1662 struct proc *p = td->td_proc;
1663 struct filedesc *fdp = p->p_fd;
1666 FILEDESC_XLOCK_ASSERT(fdp);
1668 for (i = 0; i < n; i++)
1669 if (fdalloc(td, 0, &fds[i]) != 0)
1673 for (i--; i >= 0; i--)
1674 fdunused(fdp, fds[i]);
1682 * Create a new open file structure and allocate a file decriptor for the
1683 * process that refers to it. We add one reference to the file for the
1684 * descriptor table and one reference for resultfp. This is to prevent us
1685 * being preempted and the entry in the descriptor table closed after we
1686 * release the FILEDESC lock.
1689 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags)
1694 error = falloc_noinstall(td, &fp);
1696 return (error); /* no reference held on error */
1698 error = finstall(td, fp, &fd, flags, NULL);
1700 fdrop(fp, td); /* one reference (fp only) */
1704 if (resultfp != NULL)
1705 *resultfp = fp; /* copy out result */
1707 fdrop(fp, td); /* release local reference */
1709 if (resultfd != NULL)
1716 * Create a new open file structure without allocating a file descriptor.
1719 falloc_noinstall(struct thread *td, struct file **resultfp)
1722 int maxuserfiles = maxfiles - (maxfiles / 20);
1723 static struct timeval lastfail;
1726 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
1728 if ((openfiles >= maxuserfiles &&
1729 priv_check(td, PRIV_MAXFILES) != 0) ||
1730 openfiles >= maxfiles) {
1731 if (ppsratecheck(&lastfail, &curfail, 1)) {
1732 printf("kern.maxfiles limit exceeded by uid %i, "
1733 "please see tuning(7).\n", td->td_ucred->cr_ruid);
1737 atomic_add_int(&openfiles, 1);
1738 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO);
1739 refcount_init(&fp->f_count, 1);
1740 fp->f_cred = crhold(td->td_ucred);
1741 fp->f_ops = &badfileops;
1747 * Install a file in a file descriptor table.
1750 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
1751 struct filecaps *fcaps)
1753 struct filedescent *fde;
1757 filecaps_validate(fcaps, __func__);
1758 FILEDESC_XLOCK_ASSERT(fdp);
1760 fde = &fdp->fd_ofiles[fd];
1762 seq_write_begin(&fde->fde_seq);
1765 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
1767 filecaps_move(fcaps, &fde->fde_caps);
1769 filecaps_fill(&fde->fde_caps);
1771 seq_write_end(&fde->fde_seq);
1776 finstall(struct thread *td, struct file *fp, int *fd, int flags,
1777 struct filecaps *fcaps)
1779 struct filedesc *fdp = td->td_proc->p_fd;
1784 FILEDESC_XLOCK(fdp);
1785 if ((error = fdalloc(td, 0, fd))) {
1786 FILEDESC_XUNLOCK(fdp);
1790 _finstall(fdp, fp, *fd, flags, fcaps);
1791 FILEDESC_XUNLOCK(fdp);
1796 * Build a new filedesc structure from another.
1797 * Copy the current, root, and jail root vnode references.
1799 * If fdp is not NULL, return with it shared locked.
1802 fdinit(struct filedesc *fdp, bool prepfiles)
1804 struct filedesc0 *newfdp0;
1805 struct filedesc *newfdp;
1807 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
1808 newfdp = &newfdp0->fd_fd;
1810 /* Create the file descriptor table. */
1811 FILEDESC_LOCK_INIT(newfdp);
1812 refcount_init(&newfdp->fd_refcnt, 1);
1813 refcount_init(&newfdp->fd_holdcnt, 1);
1814 newfdp->fd_cmask = CMASK;
1815 newfdp->fd_map = newfdp0->fd_dmap;
1816 newfdp->fd_lastfile = -1;
1817 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
1818 newfdp->fd_files->fdt_nfiles = NDFILE;
1823 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles)
1824 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1826 FILEDESC_SLOCK(fdp);
1827 newfdp->fd_cdir = fdp->fd_cdir;
1828 if (newfdp->fd_cdir)
1829 VREF(newfdp->fd_cdir);
1830 newfdp->fd_rdir = fdp->fd_rdir;
1831 if (newfdp->fd_rdir)
1832 VREF(newfdp->fd_rdir);
1833 newfdp->fd_jdir = fdp->fd_jdir;
1834 if (newfdp->fd_jdir)
1835 VREF(newfdp->fd_jdir);
1838 FILEDESC_SUNLOCK(fdp);
1840 while (fdp->fd_lastfile >= newfdp->fd_nfiles) {
1841 FILEDESC_SUNLOCK(fdp);
1842 fdgrowtable(newfdp, fdp->fd_lastfile + 1);
1843 FILEDESC_SLOCK(fdp);
1850 static struct filedesc *
1851 fdhold(struct proc *p)
1853 struct filedesc *fdp;
1855 PROC_LOCK_ASSERT(p, MA_OWNED);
1858 refcount_acquire(&fdp->fd_holdcnt);
1863 fddrop(struct filedesc *fdp)
1866 if (fdp->fd_holdcnt > 1) {
1867 if (refcount_release(&fdp->fd_holdcnt) == 0)
1871 FILEDESC_LOCK_DESTROY(fdp);
1872 uma_zfree(filedesc0_zone, fdp);
1876 * Share a filedesc structure.
1879 fdshare(struct filedesc *fdp)
1882 refcount_acquire(&fdp->fd_refcnt);
1887 * Unshare a filedesc structure, if necessary by making a copy
1890 fdunshare(struct thread *td)
1892 struct filedesc *tmp;
1893 struct proc *p = td->td_proc;
1895 if (p->p_fd->fd_refcnt == 1)
1898 tmp = fdcopy(p->p_fd);
1904 * Copy a filedesc structure. A NULL pointer in returns a NULL reference,
1905 * this is to ease callers, not catch errors.
1908 fdcopy(struct filedesc *fdp)
1910 struct filedesc *newfdp;
1911 struct filedescent *nfde, *ofde;
1916 newfdp = fdinit(fdp, true);
1917 /* copy all passable descriptors (i.e. not kqueue) */
1918 newfdp->fd_freefile = -1;
1919 for (i = 0; i <= fdp->fd_lastfile; ++i) {
1920 ofde = &fdp->fd_ofiles[i];
1921 if (ofde->fde_file == NULL ||
1922 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
1923 if (newfdp->fd_freefile == -1)
1924 newfdp->fd_freefile = i;
1927 nfde = &newfdp->fd_ofiles[i];
1929 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps);
1930 fhold(nfde->fde_file);
1931 fdused_init(newfdp, i);
1932 newfdp->fd_lastfile = i;
1934 if (newfdp->fd_freefile == -1)
1935 newfdp->fd_freefile = i;
1936 newfdp->fd_cmask = fdp->fd_cmask;
1937 FILEDESC_SUNLOCK(fdp);
1942 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
1943 * one of processes using it exits) and the table used to be shared.
1946 fdclearlocks(struct thread *td)
1948 struct filedesc *fdp;
1949 struct filedesc_to_leader *fdtol;
1959 MPASS(fdtol != NULL);
1961 FILEDESC_XLOCK(fdp);
1962 KASSERT(fdtol->fdl_refcount > 0,
1963 ("filedesc_to_refcount botch: fdl_refcount=%d",
1964 fdtol->fdl_refcount));
1965 if (fdtol->fdl_refcount == 1 &&
1966 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1967 for (i = 0; i <= fdp->fd_lastfile; i++) {
1968 fp = fdp->fd_ofiles[i].fde_file;
1969 if (fp == NULL || fp->f_type != DTYPE_VNODE)
1972 FILEDESC_XUNLOCK(fdp);
1973 lf.l_whence = SEEK_SET;
1976 lf.l_type = F_UNLCK;
1978 (void) VOP_ADVLOCK(vp,
1979 (caddr_t)p->p_leader, F_UNLCK,
1981 FILEDESC_XLOCK(fdp);
1986 if (fdtol->fdl_refcount == 1) {
1987 if (fdp->fd_holdleaderscount > 0 &&
1988 (p->p_leader->p_flag & P_ADVLOCK) != 0) {
1990 * close() or do_dup() has cleared a reference
1991 * in a shared file descriptor table.
1993 fdp->fd_holdleaderswakeup = 1;
1994 sx_sleep(&fdp->fd_holdleaderscount,
1995 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
1998 if (fdtol->fdl_holdcount > 0) {
2000 * Ensure that fdtol->fdl_leader remains
2001 * valid in closef().
2003 fdtol->fdl_wakeup = 1;
2004 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2009 fdtol->fdl_refcount--;
2010 if (fdtol->fdl_refcount == 0 &&
2011 fdtol->fdl_holdcount == 0) {
2012 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2013 fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2017 FILEDESC_XUNLOCK(fdp);
2019 free(fdtol, M_FILEDESC_TO_LEADER);
2023 * Release a filedesc structure.
2026 fdescfree(struct thread *td)
2029 struct filedesc0 *fdp0;
2030 struct filedesc *fdp;
2031 struct freetable *ft, *tft;
2032 struct filedescent *fde;
2034 struct vnode *cdir, *jdir, *rdir;
2044 racct_set(p, RACCT_NOFILE, 0);
2049 if (td->td_proc->p_fdtol != NULL)
2056 if (refcount_release(&fdp->fd_refcnt) == 0)
2059 FILEDESC_XLOCK(fdp);
2060 cdir = fdp->fd_cdir;
2061 fdp->fd_cdir = NULL;
2062 rdir = fdp->fd_rdir;
2063 fdp->fd_rdir = NULL;
2064 jdir = fdp->fd_jdir;
2065 fdp->fd_jdir = NULL;
2066 FILEDESC_XUNLOCK(fdp);
2068 for (i = 0; i <= fdp->fd_lastfile; i++) {
2069 fde = &fdp->fd_ofiles[i];
2073 (void) closef(fp, td);
2077 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2078 free(fdp->fd_map, M_FILEDESC);
2079 if (fdp->fd_nfiles > NDFILE)
2080 free(fdp->fd_files, M_FILEDESC);
2082 fdp0 = (struct filedesc0 *)fdp;
2083 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2084 free(ft->ft_table, M_FILEDESC);
2097 * For setugid programs, we don't want to people to use that setugidness
2098 * to generate error messages which write to a file which otherwise would
2099 * otherwise be off-limits to the process. We check for filesystems where
2100 * the vnode can change out from under us after execve (like [lin]procfs).
2102 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2103 * sufficient. We also don't check for setugidness since we know we are.
2106 is_unsafe(struct file *fp)
2110 if (fp->f_type != DTYPE_VNODE)
2114 return ((vp->v_vflag & VV_PROCDEP) != 0);
2118 * Make this setguid thing safe, if at all possible.
2121 fdsetugidsafety(struct thread *td)
2123 struct filedesc *fdp;
2127 fdp = td->td_proc->p_fd;
2128 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2129 MPASS(fdp->fd_nfiles >= 3);
2130 for (i = 0; i <= 2; i++) {
2131 fp = fdp->fd_ofiles[i].fde_file;
2132 if (fp != NULL && is_unsafe(fp)) {
2133 FILEDESC_XLOCK(fdp);
2134 knote_fdclose(td, i);
2136 * NULL-out descriptor prior to close to avoid
2137 * a race while close blocks.
2140 FILEDESC_XUNLOCK(fdp);
2141 (void) closef(fp, td);
2147 * If a specific file object occupies a specific file descriptor, close the
2148 * file descriptor entry and drop a reference on the file object. This is a
2149 * convenience function to handle a subsequent error in a function that calls
2150 * falloc() that handles the race that another thread might have closed the
2151 * file descriptor out from under the thread creating the file object.
2154 fdclose(struct thread *td, struct file *fp, int idx)
2156 struct filedesc *fdp = td->td_proc->p_fd;
2158 FILEDESC_XLOCK(fdp);
2159 if (fdp->fd_ofiles[idx].fde_file == fp) {
2161 FILEDESC_XUNLOCK(fdp);
2164 FILEDESC_XUNLOCK(fdp);
2168 * Close any files on exec?
2171 fdcloseexec(struct thread *td)
2173 struct filedesc *fdp;
2174 struct filedescent *fde;
2178 fdp = td->td_proc->p_fd;
2179 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2180 for (i = 0; i <= fdp->fd_lastfile; i++) {
2181 fde = &fdp->fd_ofiles[i];
2183 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE ||
2184 (fde->fde_flags & UF_EXCLOSE))) {
2185 FILEDESC_XLOCK(fdp);
2187 (void) closefp(fdp, i, fp, td, 0);
2188 /* closefp() drops the FILEDESC lock. */
2194 * It is unsafe for set[ug]id processes to be started with file
2195 * descriptors 0..2 closed, as these descriptors are given implicit
2196 * significance in the Standard C library. fdcheckstd() will create a
2197 * descriptor referencing /dev/null for each of stdin, stdout, and
2198 * stderr that is not already open.
2201 fdcheckstd(struct thread *td)
2203 struct filedesc *fdp;
2205 int i, error, devnull;
2207 fdp = td->td_proc->p_fd;
2208 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared"));
2209 MPASS(fdp->fd_nfiles >= 3);
2211 for (i = 0; i <= 2; i++) {
2212 if (fdp->fd_ofiles[i].fde_file != NULL)
2215 save = td->td_retval[0];
2216 if (devnull != -1) {
2217 error = do_dup(td, DUP_FIXED, devnull, i);
2219 error = kern_openat(td, AT_FDCWD, "/dev/null",
2220 UIO_SYSSPACE, O_RDWR, 0);
2222 devnull = td->td_retval[0];
2223 KASSERT(devnull == i, ("we didn't get our fd"));
2226 td->td_retval[0] = save;
2234 * Internal form of close. Decrement reference count on file structure.
2235 * Note: td may be NULL when closing a file that was being passed in a
2238 * XXXRW: Giant is not required for the caller, but often will be held; this
2239 * makes it moderately likely the Giant will be recursed in the VFS case.
2242 closef(struct file *fp, struct thread *td)
2246 struct filedesc_to_leader *fdtol;
2247 struct filedesc *fdp;
2250 * POSIX record locking dictates that any close releases ALL
2251 * locks owned by this process. This is handled by setting
2252 * a flag in the unlock to free ONLY locks obeying POSIX
2253 * semantics, and not to free BSD-style file locks.
2254 * If the descriptor was in a message, POSIX-style locks
2255 * aren't passed with the descriptor, and the thread pointer
2256 * will be NULL. Callers should be careful only to pass a
2257 * NULL thread pointer when there really is no owning
2258 * context that might have locks, or the locks will be
2261 if (fp->f_type == DTYPE_VNODE && td != NULL) {
2263 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2264 lf.l_whence = SEEK_SET;
2267 lf.l_type = F_UNLCK;
2268 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2269 F_UNLCK, &lf, F_POSIX);
2271 fdtol = td->td_proc->p_fdtol;
2272 if (fdtol != NULL) {
2274 * Handle special case where file descriptor table is
2275 * shared between multiple process leaders.
2277 fdp = td->td_proc->p_fd;
2278 FILEDESC_XLOCK(fdp);
2279 for (fdtol = fdtol->fdl_next;
2280 fdtol != td->td_proc->p_fdtol;
2281 fdtol = fdtol->fdl_next) {
2282 if ((fdtol->fdl_leader->p_flag &
2285 fdtol->fdl_holdcount++;
2286 FILEDESC_XUNLOCK(fdp);
2287 lf.l_whence = SEEK_SET;
2290 lf.l_type = F_UNLCK;
2292 (void) VOP_ADVLOCK(vp,
2293 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2295 FILEDESC_XLOCK(fdp);
2296 fdtol->fdl_holdcount--;
2297 if (fdtol->fdl_holdcount == 0 &&
2298 fdtol->fdl_wakeup != 0) {
2299 fdtol->fdl_wakeup = 0;
2303 FILEDESC_XUNLOCK(fdp);
2306 return (fdrop(fp, td));
2310 * Initialize the file pointer with the specified properties.
2312 * The ops are set with release semantics to be certain that the flags, type,
2313 * and data are visible when ops is. This is to prevent ops methods from being
2314 * called with bad data.
2317 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops)
2322 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2326 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2327 struct file **fpp, seq_t *seqp)
2330 struct filedescent *fde;
2332 struct fdescenttbl *fdt;
2337 cap_rights_t haverights;
2341 fdt = fdp->fd_files;
2342 if ((u_int)fd >= fdt->fdt_nfiles)
2345 * Fetch the descriptor locklessly. We avoid fdrop() races by
2346 * never raising a refcount above 0. To accomplish this we have
2347 * to use a cmpset loop rather than an atomic_add. The descriptor
2348 * must be re-verified once we acquire a reference to be certain
2349 * that the identity is still correct and we did not lose a race
2350 * due to preemption.
2354 seq = seq_read(fd_seq(fdt, fd));
2355 fde = &fdt->fdt_ofiles[fd];
2356 haverights = *cap_rights_fde(fde);
2358 if (!seq_consistent(fd_seq(fdt, fd), seq)) {
2363 fp = fdt->fdt_ofiles[fd].fde_file;
2368 error = cap_check(&haverights, needrightsp);
2373 count = fp->f_count;
2376 * Force a reload. Other thread could reallocate the
2377 * table before this fd was closed, so it possible that
2378 * there is a stale fp pointer in cached version.
2380 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files);
2384 * Use an acquire barrier to force re-reading of fdt so it is
2385 * refreshed for verification.
2387 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0)
2389 fdt = fdp->fd_files;
2391 if (seq_consistent_nomb(fd_seq(fdt, fd), seq))
2393 if (fp == fdt->fdt_ofiles[fd].fde_file)
2396 fdrop(fp, curthread);
2408 * Extract the file pointer associated with the specified descriptor for the
2409 * current user process.
2411 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
2414 * File's rights will be checked against the capability rights mask.
2416 * If an error occured the non-zero error is returned and *fpp is set to
2417 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is
2418 * responsible for fdrop().
2421 _fget(struct thread *td, int fd, struct file **fpp, int flags,
2422 cap_rights_t *needrightsp, seq_t *seqp)
2424 struct filedesc *fdp;
2426 cap_rights_t needrights;
2430 fdp = td->td_proc->p_fd;
2431 if (needrightsp == NULL)
2432 needrightsp = cap_rights_init(&needrights);
2433 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp);
2436 if (fp->f_ops == &badfileops) {
2442 * FREAD and FWRITE failure return EBADF as per POSIX.
2448 if ((fp->f_flag & flags) == 0)
2452 if ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
2453 ((fp->f_flag & FWRITE) != 0))
2459 KASSERT(0, ("wrong flags"));
2472 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2475 return (_fget(td, fd, fpp, 0, rightsp, NULL));
2479 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp,
2483 #ifndef CAPABILITIES
2484 error = _fget(td, fd, fpp, 0, rightsp, NULL);
2485 if (maxprotp != NULL)
2486 *maxprotp = VM_PROT_ALL;
2488 struct filedesc *fdp = td->td_proc->p_fd;
2491 MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
2493 error = _fget(td, fd, fpp, 0, rightsp, &seq);
2497 * If requested, convert capability rights to access flags.
2499 if (maxprotp != NULL)
2500 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd));
2501 if (!fd_modified(fdp, fd, seq))
2510 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2513 return (_fget(td, fd, fpp, FREAD, rightsp, NULL));
2517 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
2520 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL));
2524 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
2527 struct filedesc *fdp = td->td_proc->p_fd;
2528 #ifndef CAPABILITIES
2529 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL));
2534 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
2536 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq);
2539 error = cap_fcntl_check(fdp, fd, needfcntl);
2540 if (!fd_modified(fdp, fd, seq))
2553 * Like fget() but loads the underlying vnode, or returns an error if the
2554 * descriptor does not represent a vnode. Note that pipes use vnodes but
2555 * never have VM objects. The returned vnode will be vref()'d.
2557 * XXX: what about the unused flags ?
2560 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
2567 error = _fget(td, fd, &fp, flags, needrightsp, NULL);
2570 if (fp->f_vnode == NULL) {
2582 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2585 return (_fgetvp(td, fd, 0, rightsp, vpp));
2589 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
2590 struct filecaps *havecaps, struct vnode **vpp)
2592 struct filedesc *fdp;
2598 fdp = td->td_proc->p_fd;
2599 fp = fget_locked(fdp, fd);
2600 if (fp == NULL || fp->f_ops == &badfileops)
2604 if (needrightsp != NULL) {
2605 error = cap_check(cap_rights(fdp, fd), needrightsp);
2611 if (fp->f_vnode == NULL)
2616 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps);
2622 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2625 return (_fgetvp(td, fd, FREAD, rightsp, vpp));
2629 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
2632 return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
2637 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
2641 return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
2646 * Like fget() but loads the underlying socket, or returns an error if the
2647 * descriptor does not represent a socket.
2649 * We bump the ref count on the returned socket. XXX Also obtain the SX lock
2652 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely
2653 * on their file descriptor reference to prevent the socket from being free'd
2657 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp,
2666 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0)
2668 if (fp->f_type != DTYPE_SOCKET) {
2673 *fflagp = fp->f_flag;
2684 * Drop the reference count on the socket and XXX release the SX lock in the
2685 * future. The last reference closes the socket.
2687 * Note: fputsock() is deprecated, see comment for fgetsock().
2690 fputsock(struct socket *so)
2695 CURVNET_SET(so->so_vnet);
2701 * Handle the last reference to a file being closed.
2704 _fdrop(struct file *fp, struct thread *td)
2708 if (fp->f_count != 0)
2709 panic("fdrop: count %d", fp->f_count);
2710 error = fo_close(fp, td);
2711 atomic_subtract_int(&openfiles, 1);
2713 free(fp->f_advice, M_FADVISE);
2714 uma_zfree(file_zone, fp);
2720 * Apply an advisory lock on a file descriptor.
2722 * Just attempt to get a record lock of the requested type on the entire file
2723 * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
2725 #ifndef _SYS_SYSPROTO_H_
2733 sys_flock(struct thread *td, struct flock_args *uap)
2738 cap_rights_t rights;
2741 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp);
2744 if (fp->f_type != DTYPE_VNODE) {
2746 return (EOPNOTSUPP);
2750 lf.l_whence = SEEK_SET;
2753 if (uap->how & LOCK_UN) {
2754 lf.l_type = F_UNLCK;
2755 atomic_clear_int(&fp->f_flag, FHASLOCK);
2756 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
2759 if (uap->how & LOCK_EX)
2760 lf.l_type = F_WRLCK;
2761 else if (uap->how & LOCK_SH)
2762 lf.l_type = F_RDLCK;
2767 atomic_set_int(&fp->f_flag, FHASLOCK);
2768 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
2769 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
2775 * Duplicate the specified descriptor to a free descriptor.
2778 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
2779 int openerror, int *indxp)
2781 struct filedescent *newfde, *oldfde;
2785 KASSERT(openerror == ENODEV || openerror == ENXIO,
2786 ("unexpected error %d in %s", openerror, __func__));
2789 * If the to-be-dup'd fd number is greater than the allowed number
2790 * of file descriptors, or the fd to be dup'd has already been
2791 * closed, then reject.
2793 FILEDESC_XLOCK(fdp);
2794 if ((fp = fget_locked(fdp, dfd)) == NULL) {
2795 FILEDESC_XUNLOCK(fdp);
2799 error = fdalloc(td, 0, &indx);
2801 FILEDESC_XUNLOCK(fdp);
2806 * There are two cases of interest here.
2808 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
2810 * For ENXIO steal away the file structure from (dfd) and store it in
2811 * (indx). (dfd) is effectively closed by this operation.
2813 switch (openerror) {
2816 * Check that the mode the file is being opened for is a
2817 * subset of the mode of the existing descriptor.
2819 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
2820 fdunused(fdp, indx);
2821 FILEDESC_XUNLOCK(fdp);
2825 newfde = &fdp->fd_ofiles[indx];
2826 oldfde = &fdp->fd_ofiles[dfd];
2828 seq_write_begin(&newfde->fde_seq);
2830 memcpy(newfde, oldfde, fde_change_size);
2831 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps);
2833 seq_write_end(&newfde->fde_seq);
2838 * Steal away the file pointer from dfd and stuff it into indx.
2840 newfde = &fdp->fd_ofiles[indx];
2841 oldfde = &fdp->fd_ofiles[dfd];
2843 seq_write_begin(&newfde->fde_seq);
2845 memcpy(newfde, oldfde, fde_change_size);
2846 oldfde->fde_file = NULL;
2849 seq_write_end(&newfde->fde_seq);
2853 FILEDESC_XUNLOCK(fdp);
2859 * Scan all active processes and prisons to see if any of them have a current
2860 * or root directory of `olddp'. If so, replace them with the new mount point.
2863 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
2865 struct filedesc *fdp;
2870 if (vrefcnt(olddp) == 1)
2873 sx_slock(&allproc_lock);
2874 FOREACH_PROC_IN_SYSTEM(p) {
2880 FILEDESC_XLOCK(fdp);
2881 if (fdp->fd_cdir == olddp) {
2883 fdp->fd_cdir = newdp;
2886 if (fdp->fd_rdir == olddp) {
2888 fdp->fd_rdir = newdp;
2891 if (fdp->fd_jdir == olddp) {
2893 fdp->fd_jdir = newdp;
2896 FILEDESC_XUNLOCK(fdp);
2899 sx_sunlock(&allproc_lock);
2900 if (rootvnode == olddp) {
2905 mtx_lock(&prison0.pr_mtx);
2906 if (prison0.pr_root == olddp) {
2908 prison0.pr_root = newdp;
2911 mtx_unlock(&prison0.pr_mtx);
2912 sx_slock(&allprison_lock);
2913 TAILQ_FOREACH(pr, &allprison, pr_list) {
2914 mtx_lock(&pr->pr_mtx);
2915 if (pr->pr_root == olddp) {
2917 pr->pr_root = newdp;
2920 mtx_unlock(&pr->pr_mtx);
2922 sx_sunlock(&allprison_lock);
2927 struct filedesc_to_leader *
2928 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader)
2930 struct filedesc_to_leader *fdtol;
2932 fdtol = malloc(sizeof(struct filedesc_to_leader),
2933 M_FILEDESC_TO_LEADER, M_WAITOK);
2934 fdtol->fdl_refcount = 1;
2935 fdtol->fdl_holdcount = 0;
2936 fdtol->fdl_wakeup = 0;
2937 fdtol->fdl_leader = leader;
2939 FILEDESC_XLOCK(fdp);
2940 fdtol->fdl_next = old->fdl_next;
2941 fdtol->fdl_prev = old;
2942 old->fdl_next = fdtol;
2943 fdtol->fdl_next->fdl_prev = fdtol;
2944 FILEDESC_XUNLOCK(fdp);
2946 fdtol->fdl_next = fdtol;
2947 fdtol->fdl_prev = fdtol;
2953 * Get file structures globally.
2956 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
2959 struct filedesc *fdp;
2964 error = sysctl_wire_old_buffer(req, 0);
2967 if (req->oldptr == NULL) {
2969 sx_slock(&allproc_lock);
2970 FOREACH_PROC_IN_SYSTEM(p) {
2972 if (p->p_state == PRS_NEW) {
2980 /* overestimates sparse tables. */
2981 if (fdp->fd_lastfile > 0)
2982 n += fdp->fd_lastfile;
2985 sx_sunlock(&allproc_lock);
2986 return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
2989 bzero(&xf, sizeof(xf));
2990 xf.xf_size = sizeof(xf);
2991 sx_slock(&allproc_lock);
2992 FOREACH_PROC_IN_SYSTEM(p) {
2994 if (p->p_state == PRS_NEW) {
2998 if (p_cansee(req->td, p) != 0) {
3002 xf.xf_pid = p->p_pid;
3003 xf.xf_uid = p->p_ucred->cr_uid;
3008 FILEDESC_SLOCK(fdp);
3009 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) {
3010 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3014 xf.xf_data = fp->f_data;
3015 xf.xf_vnode = fp->f_vnode;
3016 xf.xf_type = fp->f_type;
3017 xf.xf_count = fp->f_count;
3019 xf.xf_offset = foffset_get(fp);
3020 xf.xf_flag = fp->f_flag;
3021 error = SYSCTL_OUT(req, &xf, sizeof(xf));
3025 FILEDESC_SUNLOCK(fdp);
3030 sx_sunlock(&allproc_lock);
3034 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
3035 0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
3037 #ifdef KINFO_FILE_SIZE
3038 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
3042 xlate_fflags(int fflags)
3044 static const struct {
3047 } fflags_table[] = {
3048 { FAPPEND, KF_FLAG_APPEND },
3049 { FASYNC, KF_FLAG_ASYNC },
3050 { FFSYNC, KF_FLAG_FSYNC },
3051 { FHASLOCK, KF_FLAG_HASLOCK },
3052 { FNONBLOCK, KF_FLAG_NONBLOCK },
3053 { FREAD, KF_FLAG_READ },
3054 { FWRITE, KF_FLAG_WRITE },
3055 { O_CREAT, KF_FLAG_CREAT },
3056 { O_DIRECT, KF_FLAG_DIRECT },
3057 { O_EXCL, KF_FLAG_EXCL },
3058 { O_EXEC, KF_FLAG_EXEC },
3059 { O_EXLOCK, KF_FLAG_EXLOCK },
3060 { O_NOFOLLOW, KF_FLAG_NOFOLLOW },
3061 { O_SHLOCK, KF_FLAG_SHLOCK },
3062 { O_TRUNC, KF_FLAG_TRUNC }
3068 for (i = 0; i < nitems(fflags_table); i++)
3069 if (fflags & fflags_table[i].fflag)
3070 kflags |= fflags_table[i].kf_fflag;
3074 /* Trim unused data from kf_path by truncating the structure size. */
3076 pack_kinfo(struct kinfo_file *kif)
3079 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
3080 strlen(kif->kf_path) + 1;
3081 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
3085 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
3086 struct kinfo_file *kif, struct filedesc *fdp)
3090 bzero(kif, sizeof(*kif));
3092 /* Set a default type to allow for empty fill_kinfo() methods. */
3093 kif->kf_type = KF_TYPE_UNKNOWN;
3094 kif->kf_flags = xlate_fflags(fp->f_flag);
3095 if (rightsp != NULL)
3096 kif->kf_cap_rights = *rightsp;
3098 cap_rights_init(&kif->kf_cap_rights);
3100 kif->kf_ref_count = fp->f_count;
3101 kif->kf_offset = foffset_get(fp);
3104 * This may drop the filedesc lock, so the 'fp' cannot be
3105 * accessed after this call.
3107 error = fo_fill_kinfo(fp, kif, fdp);
3109 kif->kf_status |= KF_ATTR_VALID;
3114 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
3115 struct kinfo_file *kif)
3119 bzero(kif, sizeof(*kif));
3121 kif->kf_type = KF_TYPE_VNODE;
3122 error = vn_fill_kinfo_vnode(vp, kif);
3124 kif->kf_status |= KF_ATTR_VALID;
3125 kif->kf_flags = xlate_fflags(fflags);
3126 cap_rights_init(&kif->kf_cap_rights);
3128 kif->kf_ref_count = -1;
3129 kif->kf_offset = -1;
3134 struct export_fd_buf {
3135 struct filedesc *fdp;
3138 struct kinfo_file kif;
3142 export_kinfo_to_sb(struct export_fd_buf *efbuf)
3144 struct kinfo_file *kif;
3147 if (efbuf->remainder != -1) {
3148 if (efbuf->remainder < kif->kf_structsize) {
3149 /* Terminate export. */
3150 efbuf->remainder = 0;
3153 efbuf->remainder -= kif->kf_structsize;
3155 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM);
3159 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
3160 struct export_fd_buf *efbuf)
3164 if (efbuf->remainder == 0)
3166 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp);
3167 FILEDESC_SUNLOCK(efbuf->fdp);
3168 error = export_kinfo_to_sb(efbuf);
3169 FILEDESC_SLOCK(efbuf->fdp);
3174 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
3175 struct export_fd_buf *efbuf)
3179 if (efbuf->remainder == 0)
3181 if (efbuf->fdp != NULL)
3182 FILEDESC_SUNLOCK(efbuf->fdp);
3183 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif);
3184 error = export_kinfo_to_sb(efbuf);
3185 if (efbuf->fdp != NULL)
3186 FILEDESC_SLOCK(efbuf->fdp);
3191 * Store a process file descriptor information to sbuf.
3193 * Takes a locked proc as argument, and returns with the proc unlocked.
3196 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3199 struct filedesc *fdp;
3200 struct export_fd_buf *efbuf;
3201 struct vnode *cttyvp, *textvp, *tracevp;
3203 cap_rights_t rights;
3205 PROC_LOCK_ASSERT(p, MA_OWNED);
3208 tracevp = p->p_tracevp;
3209 if (tracevp != NULL)
3212 textvp = p->p_textvp;
3215 /* Controlling tty. */
3217 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
3218 cttyvp = p->p_pgrp->pg_session->s_ttyvp;
3224 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3227 efbuf->remainder = maxlen;
3228 if (tracevp != NULL)
3229 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE,
3232 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf);
3234 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE,
3240 FILEDESC_SLOCK(fdp);
3241 /* working directory */
3242 if (fdp->fd_cdir != NULL) {
3244 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
3246 /* root directory */
3247 if (fdp->fd_rdir != NULL) {
3249 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf);
3251 /* jail directory */
3252 if (fdp->fd_jdir != NULL) {
3254 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf);
3256 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3257 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3260 rights = *cap_rights(fdp, i);
3261 #else /* !CAPABILITIES */
3262 cap_rights_init(&rights);
3265 * Create sysctl entry. It is OK to drop the filedesc
3266 * lock inside of export_file_to_sb() as we will
3267 * re-validate and re-evaluate its properties when the
3270 error = export_file_to_sb(fp, i, &rights, efbuf);
3271 if (error != 0 || efbuf->remainder == 0)
3274 FILEDESC_SUNLOCK(fdp);
3277 free(efbuf, M_TEMP);
3281 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5)
3284 * Get per-process file descriptors for use by procstat(1), et al.
3287 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
3292 int error, error2, *name;
3296 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
3297 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3298 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3303 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3304 error = kern_proc_filedesc_out(p, &sb, maxlen);
3305 error2 = sbuf_finish(&sb);
3307 return (error != 0 ? error : error2);
3310 #ifdef KINFO_OFILE_SIZE
3311 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
3314 #ifdef COMPAT_FREEBSD7
3316 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
3319 okif->kf_structsize = sizeof(*okif);
3320 okif->kf_type = kif->kf_type;
3321 okif->kf_fd = kif->kf_fd;
3322 okif->kf_ref_count = kif->kf_ref_count;
3323 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
3324 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
3325 KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
3326 okif->kf_offset = kif->kf_offset;
3327 okif->kf_vnode_type = kif->kf_vnode_type;
3328 okif->kf_sock_domain = kif->kf_sock_domain;
3329 okif->kf_sock_type = kif->kf_sock_type;
3330 okif->kf_sock_protocol = kif->kf_sock_protocol;
3331 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
3332 okif->kf_sa_local = kif->kf_sa_local;
3333 okif->kf_sa_peer = kif->kf_sa_peer;
3337 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
3338 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req)
3343 FILEDESC_SUNLOCK(fdp);
3344 export_vnode_to_kinfo(vp, type, 0, kif);
3345 kinfo_to_okinfo(kif, okif);
3346 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3347 FILEDESC_SLOCK(fdp);
3352 * Get per-process file descriptors for use by procstat(1), et al.
3355 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
3357 struct kinfo_ofile *okif;
3358 struct kinfo_file *kif;
3359 struct filedesc *fdp;
3360 int error, i, *name;
3365 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3372 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
3373 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
3374 FILEDESC_SLOCK(fdp);
3375 if (fdp->fd_cdir != NULL)
3376 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif,
3378 if (fdp->fd_rdir != NULL)
3379 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif,
3381 if (fdp->fd_jdir != NULL)
3382 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif,
3384 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) {
3385 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL)
3387 export_file_to_kinfo(fp, i, NULL, kif, fdp);
3388 FILEDESC_SUNLOCK(fdp);
3389 kinfo_to_okinfo(kif, okif);
3390 error = SYSCTL_OUT(req, okif, sizeof(*okif));
3391 FILEDESC_SLOCK(fdp);
3395 FILEDESC_SUNLOCK(fdp);
3402 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
3403 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
3404 "Process ofiledesc entries");
3405 #endif /* COMPAT_FREEBSD7 */
3408 vntype_to_kinfo(int vtype)
3413 } vtypes_table[] = {
3414 { VBAD, KF_VTYPE_VBAD },
3415 { VBLK, KF_VTYPE_VBLK },
3416 { VCHR, KF_VTYPE_VCHR },
3417 { VDIR, KF_VTYPE_VDIR },
3418 { VFIFO, KF_VTYPE_VFIFO },
3419 { VLNK, KF_VTYPE_VLNK },
3420 { VNON, KF_VTYPE_VNON },
3421 { VREG, KF_VTYPE_VREG },
3422 { VSOCK, KF_VTYPE_VSOCK }
3427 * Perform vtype translation.
3429 for (i = 0; i < nitems(vtypes_table); i++)
3430 if (vtypes_table[i].vtype == vtype)
3431 return (vtypes_table[i].kf_vtype);
3433 return (KF_VTYPE_UNKNOWN);
3436 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
3437 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
3438 "Process filedesc entries");
3441 * Store a process current working directory information to sbuf.
3443 * Takes a locked proc as argument, and returns with the proc unlocked.
3446 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen)
3448 struct filedesc *fdp;
3449 struct export_fd_buf *efbuf;
3452 PROC_LOCK_ASSERT(p, MA_OWNED);
3459 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
3462 efbuf->remainder = maxlen;
3464 FILEDESC_SLOCK(fdp);
3465 if (fdp->fd_cdir == NULL)
3469 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD,
3472 FILEDESC_SUNLOCK(fdp);
3474 free(efbuf, M_TEMP);
3479 * Get per-process current working directory.
3482 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
3487 int error, error2, *name;
3491 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
3492 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
3493 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
3498 maxlen = req->oldptr != NULL ? req->oldlen : -1;
3499 error = kern_proc_cwd_out(p, &sb, maxlen);
3500 error2 = sbuf_finish(&sb);
3502 return (error != 0 ? error : error2);
3505 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
3506 sysctl_kern_proc_cwd, "Process current working directory");
3510 * For the purposes of debugging, generate a human-readable string for the
3514 file_type_to_name(short type)
3544 * For the purposes of debugging, identify a process (if any, perhaps one of
3545 * many) that references the passed file in its file descriptor array. Return
3548 static struct proc *
3549 file_to_first_proc(struct file *fp)
3551 struct filedesc *fdp;
3555 FOREACH_PROC_IN_SYSTEM(p) {
3556 if (p->p_state == PRS_NEW)
3561 for (n = 0; n <= fdp->fd_lastfile; n++) {
3562 if (fp == fdp->fd_ofiles[n].fde_file)
3570 db_print_file(struct file *fp, int header)
3575 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n",
3576 "File", "Type", "Data", "Flag", "GCFl", "Count",
3577 "MCount", "Vnode", "FPID", "FCmd");
3578 p = file_to_first_proc(fp);
3579 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp,
3580 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag,
3581 0, fp->f_count, 0, fp->f_vnode,
3582 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
3585 DB_SHOW_COMMAND(file, db_show_file)
3590 db_printf("usage: show file <addr>\n");
3593 fp = (struct file *)addr;
3594 db_print_file(fp, 1);
3597 DB_SHOW_COMMAND(files, db_show_files)
3599 struct filedesc *fdp;
3606 FOREACH_PROC_IN_SYSTEM(p) {
3607 if (p->p_state == PRS_NEW)
3609 if ((fdp = p->p_fd) == NULL)
3611 for (n = 0; n <= fdp->fd_lastfile; ++n) {
3612 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
3614 db_print_file(fp, header);
3621 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW,
3622 &maxfilesperproc, 0, "Maximum files allowed open per process");
3624 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW,
3625 &maxfiles, 0, "Maximum number of files");
3627 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
3628 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files");
3632 filelistinit(void *dummy)
3635 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
3636 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
3637 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
3638 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3639 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
3641 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
3643 /*-------------------------------------------------------------------*/
3646 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
3647 int flags, struct thread *td)
3654 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3662 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
3670 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
3678 badfo_kqfilter(struct file *fp, struct knote *kn)
3685 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
3693 badfo_close(struct file *fp, struct thread *td)
3700 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3708 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3716 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3717 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3718 int kflags, struct thread *td)
3725 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
3731 struct fileops badfileops = {
3732 .fo_read = badfo_readwrite,
3733 .fo_write = badfo_readwrite,
3734 .fo_truncate = badfo_truncate,
3735 .fo_ioctl = badfo_ioctl,
3736 .fo_poll = badfo_poll,
3737 .fo_kqfilter = badfo_kqfilter,
3738 .fo_stat = badfo_stat,
3739 .fo_close = badfo_close,
3740 .fo_chmod = badfo_chmod,
3741 .fo_chown = badfo_chown,
3742 .fo_sendfile = badfo_sendfile,
3743 .fo_fill_kinfo = badfo_fill_kinfo,
3747 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
3748 int flags, struct thread *td)
3751 return (EOPNOTSUPP);
3755 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
3763 invfo_ioctl(struct file *fp, u_long com, void *data,
3764 struct ucred *active_cred, struct thread *td)
3771 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
3775 return (poll_no_poll(events));
3779 invfo_kqfilter(struct file *fp, struct knote *kn)
3786 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
3794 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
3802 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
3803 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
3804 int kflags, struct thread *td)
3810 /*-------------------------------------------------------------------*/
3813 * File Descriptor pseudo-device driver (/dev/fd/).
3815 * Opening minor device N dup()s the file (if any) connected to file
3816 * descriptor N belonging to the calling process. Note that this driver
3817 * consists of only the ``open()'' routine, because all subsequent
3818 * references to this file will be direct to the other driver.
3820 * XXX: we could give this one a cloning event handler if necessary.
3825 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
3829 * XXX Kludge: set curthread->td_dupfd to contain the value of the
3830 * the file descriptor being sought for duplication. The error
3831 * return ensures that the vnode for this device will be released
3832 * by vn_open. Open will detect this special error and take the
3833 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
3834 * will simply report the error.
3836 td->td_dupfd = dev2unit(dev);
3840 static struct cdevsw fildesc_cdevsw = {
3841 .d_version = D_VERSION,
3847 fildesc_drvinit(void *unused)
3851 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
3852 UID_ROOT, GID_WHEEL, 0666, "fd/0");
3853 make_dev_alias(dev, "stdin");
3854 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
3855 UID_ROOT, GID_WHEEL, 0666, "fd/1");
3856 make_dev_alias(dev, "stdout");
3857 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
3858 UID_ROOT, GID_WHEEL, 0666, "fd/2");
3859 make_dev_alias(dev, "stderr");
3862 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);